2015-09-19 28 views
0

我已經創建了一個Android應用程序,我使用此代碼從服務器接收json對象,並且需要從android發送來自android活動的json對象我該怎麼辦? 強大的文本如何發送json對象並接收響應json對象android在單個代碼中

class GetDataJSON extends AsyncTask<String, Void, String> { 
    private Dialog loadingDialog; 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     loadingDialog = ProgressDialog.show(anscheck.this, "Please wait", 
       "Loading..."); 
    } 

    @Override 
    protected String doInBackground(String... params) { 
     InputStream inputStream = null; 

     String result = null; 

     try { 

      DefaultHttpClient httpclient = new DefaultHttpClient(
        new BasicHttpParams()); 
      HttpPost httppost = new HttpPost(url); 

      httppost.setHeader("Content-type", "application/json"); 

      HttpResponse response = httpclient.execute(httppost); 
      HttpEntity entity = response.getEntity(); 

      inputStream = entity.getContent(); 
      // json is UTF-8 by default 
      BufferedReader reader = new BufferedReader(new InputStreamReader(
        inputStream, "UTF-8"), 8); 
      StringBuilder sb = new StringBuilder(); 

      String line = null; 
      while ((line = reader.readLine()) != null) 

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

      } 
      result = sb.toString(); 
     } catch (Exception e) { 
      // Oops 
     } finally { 
      try { 
       if (inputStream != null) 
        inputStream.close(); 
      } catch (Exception squish) { 
      } 
     } 
     return result; 
    } 

    @Override 
    protected void onPostExecute(String result) { 

     loadingDialog.dismiss(); 
     String s = result.trim(); 

     { 
      myJSON = result; 
      showList(); 
     } 
    } 
} 
+0

您可以使用'StringEntity'發佈'JSON'服務器 –

回答

0

您可以創建你需要發佈到服務器並將其設置爲StringEntity你`HttpPost」方法調用, 下面我提供一些參考代碼,任何數據的JSONObject

首先創建您需要發佈即喜歡你的JSON數據

public String loginArray() { 
    JSONObject jsonObject = new JSONObject(); 
    try { 
     jsonObject.put("email", uName); 
     jsonObject.put("password", password); 
    } catch (JSONException exception) { 

    } 

    UiUtils.showLog(jsonObject.toString()); 
    return jsonObject.toString(); 
} 

現在將其設置爲StringEntityHttpPost我。 Ë

httppost.setEntity(new StringEntity(loginArray()) 

寫這行之前或之後設置header