【问题标题】:How to send data to server through JSON如何通过 JSON 向服务器发送数据
【发布时间】: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://&lt;my server address&gt;/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);
    }
    }
 ?>

【问题讨论】:

  • 我用谷歌搜索了它。这就是我找到这段代码的方式。我想知道这段代码有什么问题
  • 显示您请求的服务器页面的代码,因为它应该处理您发送的输入然后返回响应
  • 我已经为我的服务器页面添加了代码。我是服务器脚本的新手,这是我从网络引用的代码。希望这是您要求的代码。
  • 你的数据库中的值都是字符串吗?

标签: android json http-post


【解决方案1】:

BufferedReader br= 新的 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();  

你可以使用一个简单的方法来代替编写这些代码块

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

将此行放在 client.execute 方法下方和此 write logcat.verbose 语句下方。

【讨论】:

  • 是的,先生,它说:`未知的 MySQL 服务器主机 'DB_HOST' (110) 11-05 20:51:27.243 13821-13912/? W/dalvikvm: threadid=18: thread exiting with uncaught exception (group=0x415afbc0)' Caused by: java.lang.IllegalStateException: Content has been used
  • 您指定的主机不正确。您在 db 主机变量中分配了什么值
  • define('DB_HOST', 'localhost'); config.php 文件中的这一行。localhost 是服务器的名称。我在我的 ubuntu 笔记本电脑中使用灯服务器。并在其中设置了 phpMyadmin。
  • 我使用 127.0.0.1 而不是 localhost 现在它继续执行 doInBackground 进程并且永不退出。
【解决方案2】:

您使用哪个后端将数据发送到服务器 php 或 servlet jsp?如果要发送,则应将数据包装到具有数据类型名称值对的数组列表中。但在此之前,请告诉我您使用的是哪个后端。

【讨论】:

  • 我已经编辑了我的问题,请看一下。谢谢。
  • 而且我没有从服务器得到任何反馈,我在我的代码中使用了 toast。但是没有显示任何消息。
  • 为什么您没有在 php 中为 get 请求编写代码,这可能是您正在执行 get 请求,并且由于您没有在 php 中为 get 请求编写代码,因此它什么也没有返回。只需使用 logcat 打印行变量值。
  • 请求代码是指连接数据库的代码吗?如果是,那么我有一个,我会在这里发布。
  • print the line variable value using logcat.- 我不知道该怎么做。
【解决方案3】:

请注意,如果列类型不是 nvarchar,则值应该没有这些 ' '
例如,如果列 mobile 是 int 类型,那么它应该这样写:

$Mobile not '$Mobile'

像这样:

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

【讨论】:

    【解决方案4】:

    还有一件事你不能在 doInBackground 方法中显示 toast。因为 doInBackground 方法在后台运行,而 toast 处理 ui 线程。因此,请将您的 toast 语句放在 doInBackground 之外或 onPostExecute 方法内。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-20
      • 2017-01-26
      • 2013-11-17
      • 1970-01-01
      • 2019-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多