【发布时间】:2015-11-04 16:53:46
【问题描述】:
我对 JSON 完全陌生。我已经学会了如何通过 JSON 从服务器获取数据。我正在尝试创建一个注册活动并尝试发送用户输入的数据。
注册有以下提要:
1.名称
2.学院名称
3.手机号
4.电子邮件ID
我想发送以下格式的数据:
{
"register": [
{
"username": "abcd",
"college name": "kkddge",
"email": "example@gmail.com",
"Mobile no.": "1234567890",
}
]
}
我已经从我在 youtube 上看到的视频中尝试了这样的代码。我不知道这里实际发生了什么:
我的ServiceHandler.java 文件。
package com.defcomdevs.invento16;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
public class ServiceHandler {
static InputStream inputStream=null;
static String response=null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler(){
}
public String makeServiceCall (String url ,int method){
return this.makeServiceCall(url, method);
}
public String makeServiceCall (String url, int method ,List<NameValuePair> params){
try{
DefaultHttpClient httpClient=new DefaultHttpClient();
HttpEntity httpEntity =null;
HttpResponse httpResponse = null;
if(method == POST){
HttpPost httpPost = new HttpPost(url);
if (params!=null){
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
}else if (method==GET){
if(params!= null){
String paramString=URLEncodedUtils.format(params,"utf-8");
url += "?" +paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse= httpClient.execute(httpGet);
}
httpEntity=httpResponse.getEntity();
inputStream=httpEntity.getContent();
}catch (UnsupportedEncodingException e){
e.printStackTrace();
}
catch (ClientProtocolException c){
c.printStackTrace();
}
catch (IOException e1){
e1.printStackTrace();
}
try{
BufferedReader br= new BufferedReader
(new InputStreamReader(inputStream,"UTF-8"),8);
StringBuilder sb=new StringBuilder();
String line = null;
while ((line = br.readLine())!=null){
sb.append(line + "\n");
}
inputStream.close();
} catch (Exception e){
Log.e("Buffer Error","Error:" + e.toString());
}
return response;
}
}
调用服务处理程序的代码部分
private class InventoRegistration extends AsyncTask{
@Override
protected Object doInBackground(Object[] params) {
//Toast.makeText(context,"Entered doInBackGround",Toast.LENGTH_SHORT).show();
List<NameValuePair> postparams = new ArrayList<NameValuePair>();
postparams.add(new BasicNameValuePair("Name",username));
postparams.add(new BasicNameValuePair("College",usercollege));
postparams.add(new BasicNameValuePair("Mobile no.",usermobile));
postparams.add(new BasicNameValuePair("Email",useremail));
ServiceHandler serviceHandler = new ServiceHandler();
String json = serviceHandler.makeServiceCall(url,ServiceHandler.POST,postparams);
if (json!=null){
try{
JSONObject jsonObject = new JSONObject(json);
boolean error= jsonObject.getBoolean("error");
//checking if error node in JSON
if(!error){
//new Category created
Toast.makeText(context,"Registered Successfully",Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(context,"Registration Unsuccessfull",Toast.LENGTH_LONG).show();
}
}catch (JSONException j){
j.printStackTrace();
}
}else{
Log.e("JSON data","JSON data error");
}
return null;
}
}
我的服务器端脚本文件inventoRegister.php
<?php
include_once './DbConnect.php';
function createNewPrediction() {
$response = array();
$Name = $_POST["Name"];
$College = $_POST["College"];
$Mobile = $_POST["Mobile no."];
$Email = $_POST["Email"];
$db = new DbConnect();
// mysql query
$query = "INSERT INTO Register(Name,College,Mobile,Email) VALUES('$Name','$College','$Mobile','$Email')";
$result = mysql_query($query) or die(mysql_error());
if ($result) {
$response["error"] = false;
$response["message"] = " added successfully!";
} else {
$response["error"] = true;
$response["message"] = "Failed to add!";
}
// echo json response
echo json_encode($response);
}
createNewPrediction();
?>
此代码不起作用。由于未显示数据。也没有响应。我已将响应作为敬酒给出,您可以看到。但也没有显示敬酒。
网址是我的服务器网址,它是我本地电脑上的服务器。我检查了连接,一切都是正确的。
我在这里使用的网址是:http://<my server address>/inventoRegister.php。这是服务器地址的写入方式吗?任何有关代码的帮助将不胜感激。
我的 DbConnect.php 文件:
<?php
class DbConnect {
private $conn;
function __construct() {
// connecting to database
$this->connect();
}
function __destruct() {
$this->close();
}
function connect() {
include_once dirname(__FILE__) . './Config.php';
$this->conn = mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD) or die(mysql_error());
mysql_select_db(DB_NAME) or die(mysql_error());
// returing connection resource
return $this->conn;
}
// Close function
function close() {
// close db connection
mysql_close($this->conn);
}
}
?>
【问题讨论】:
-
我用谷歌搜索了它。这就是我找到这段代码的方式。我想知道这段代码有什么问题
-
显示您请求的服务器页面的代码,因为它应该处理您发送的输入然后返回响应
-
我已经为我的服务器页面添加了代码。我是服务器脚本的新手,这是我从网络引用的代码。希望这是您要求的代码。
-
你的数据库中的值都是字符串吗?