2013-07-31 95 views
0

我不知道我是否正確使用POST方式發送JSON數據。我想在JSONObject「ReportCode」上發送一個數據。到目前爲止我得到了這個?請告訴我我的代碼有什麼問題,以及我需要做什麼來以JSON傳遞數據。謝謝。如何在Android中使用POST發送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)); 

    } 
} 

} 
+1

它沒有通過,或者是什麼問題? –

+0

我得到這個錯誤07-31 13:33:47.906:E/ClientServerDemo(6803):org.apache.http.client.ClientProtocolException at HttpResponse httpResponse = httpClient.execute(httpPost); – NewDroidDev

+0

檢查[此鏈接](http://stackoverflow.com/a/13149239/430480)對於類似問題 – Rajeev

回答

0

如果您看到DefaultHttpClient用於爲.execute函數的所有有效參數的選項,然後他們都不只是有一個HttpPost對象作爲輸入參數。所以這就是你遇到錯誤的原因。嘗試使輸入參數正確。希望能幫助你理解這個問題。

+0

你可以舉例以便我能夠很好地理解謝謝 – NewDroidDev

相關問題