如何通过JSON

时间:2015-11-04 16:53:47

标签: android json http-post

我对JSON完全陌生。我已经学会了如何通过JSON从服务器获取数据。我正在尝试创建注册活动并尝试按用户输入的方式发送数据。 / p>

注册有以下Feed:

1.Name

2.College name

3.Mobile no。

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;
 }
 }

调用servicehandler的代码部分

    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);
    }
    }
 ?>

4 个答案:

答案 0 :(得分:1)

BufferedReader br = new BufferedReader                 (new InputStreamReader(inputStream,&#34; UTF-8&#34;),8);

    StringBuilder sb=new StringBuilder();
    String line = null;
    while ((line = br.readLine())!=null){

        sb.append(line + "\n");
    }

    inputStream.close();  

而不是写这些行,你可以使用一个简单的方法

String line = EntityUtils.toString(httpResponse.getEntity())这会将您的回复转换为字符串。

将此行放在client.execute方法下面,并在此处写下logcat.verbose语句。

答案 1 :(得分:0)

您使用哪个后端将数据发送到服务器php或servlet jsp?如果要发送,则应将数据包装到数据类型为namevalue对的数组列表中。但在那之前请告诉我你正在使用哪个后端。

答案 2 :(得分:0)

请注意,如果列类型不是nvarchar,则值应该没有这些&#39; &#39;
例如,如果列mobile类型为int,那么它应该写成:

$Mobile not '$Mobile'
像这样:

"INSERT INTO Register(Name,College,Mobile,Email) VALUES('$Name','$College',$Mobile,'$Email')"

答案 3 :(得分:0)

还有一件事你不能在doInBackground方法中显示toast。因为doInBackground方法在后台运行并且toast处理ui线程。所以把你的toast语句放在doInBackground之外或onPostExecute方法之内。