【问题标题】:How to use POST in sending data in JSON in android?如何使用 POST 在 android 中以 JSON 格式发送数据?
【发布时间】:2013-07-31 14:12:25
【问题描述】:

我不知道我使用 POST 以 JSON 格式发送数据的方法是否正确。我想在 JSONObject“ReportCode”上发送一个数据。到目前为止我得到了这个?请告诉我我的代码有什么问题以及我应该怎么做才能以 JSON 格式传递数据。谢谢。

public class DoPost extends AsyncTask<String, Void, Boolean>
{
Exception exception = null;
private ProgressDialog progressDialog;
Context mContext = null;
BufferedReader in;
InputStream is;

public DoPost(Context context) {

    mContext = context;

}

protected void onPreExecute() 
{     
    progressDialog = new ProgressDialog(mContext);
    progressDialog.setMessage("Validating....");
    progressDialog.show();              
    progressDialog.setCancelable(false);
}

@Override
protected Boolean doInBackground(String... arg0) 
{
    JSONObject jObject = new JSONObject();
    try{
        jObject.put("ReportCode","13-T001");

        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("ReportData", jObject.toString()));

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost("http://phsjulchs4.tias.com.ph:1217/api/report");
        httpPost.setEntity(new UrlEncodedFormEntity(pairs, "UTF-8"));
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();


    }catch (Exception e){
    Log.e("ClientServerDemo", "Error:", e);
    exception = e;
    //Toast.makeText(getApplicationContext(), e.getMessage().toString(), 5).show();
    }

return true;    

}

@Override
protected void onPostExecute(Boolean valid)
{
    progressDialog.dismiss();   
    //Update the UI
    if(exception != null){

        Toast.makeText(mContext, "Sent", 6).show();
    }else{
    //  mContext.startActivity(new Intent(mContext, S_2nd_Main.class));

    }
}

}

【问题讨论】:

  • 是不通过还是什么问题?
  • 我收到了这个错误 07-31 13:33:47.906: E/ClientServerDemo(6803): org.apache.http.client.ClientProtocolException at HttpResponse httpResponse = httpClient.execute(httpPost);跨度>
  • 检查this link是否有类似问题

标签: android json web-services post


【解决方案1】:

如果您在DefaultHttpClient 上看到.execute 函数的所有有效参数的选项,那么它们中没有一个只有一个HttpPost 对象作为输入参数。这就是您遇到错误的原因。尝试使输入参数正确。希望能帮助你理解问题。

【讨论】:

    猜你喜欢
    • 2011-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-10
    • 1970-01-01
    • 2012-04-02
    • 1970-01-01
    相关资源
    最近更新 更多