2012-10-12 60 views
0

我需要從移動android應用向服務器端應用發送http POST請求。 該請求需要包含正文中的json消息和一些鍵值參數。 我嘗試寫這個方法:通過http發送請求發送鍵值參數和json消息體

public static String makePostRequest(String url, String body, BasicHttpParams params) throws ClientProtocolException, IOException { 
     Logger.i(HttpClientAndroid.class, "Make post request"); 
     HttpPost httpPost = new HttpPost(url); 
     StringEntity entity = new StringEntity(body); 
     httpPost.setParams(params); 
     httpPost.setEntity(entity); 
     HttpResponse response = getHttpClient().execute(httpPost); 
     return handleResponse(response); 
    } 

這裏我設置參數應用要求throught方法setParams並設置JSON身體throught setEntity。 但這是行不通的。 有人可以幫我嗎?

回答

1

可以使用NameValuePair做到這一點..........

下面是我的項目,我用的NameValuePair來發送的XML數據,並接收XML響應的代碼,這將提供有關如何將其與JSON一起使用的一些想法。

public String postData(String url, String xmlQuery) { 



    final String urlStr = url; 
    final String xmlStr = xmlQuery; 
    final StringBuilder sb = new StringBuilder(); 


    Thread t1 = new Thread(new Runnable() { 

     public void run() { 

      HttpClient httpclient = new DefaultHttpClient(); 

      HttpPost httppost = new HttpPost(urlStr); 


      try { 

       List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
         1); 
       nameValuePairs.add(new BasicNameValuePair("xml", xmlStr)); 

       httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

       HttpResponse response = httpclient.execute(httppost); 

       Log.d("Vivek", response.toString()); 

       HttpEntity entity = response.getEntity(); 
       InputStream i = entity.getContent(); 

       Log.d("Vivek", i.toString()); 
       InputStreamReader isr = new InputStreamReader(i); 

       BufferedReader br = new BufferedReader(isr); 

       String s = null; 


       while ((s = br.readLine()) != null) { 

        Log.d("YumZing", s); 
        sb.append(s); 
       } 


       Log.d("Check Now",sb+""); 




      } catch (ClientProtocolException e) { 

       e.printStackTrace(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 

    }); 

    t1.start(); 
    try { 
     t1.join(); 
    } catch (InterruptedException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 


    System.out.println("Getting from Post Data Method "+sb.toString()); 

    return sb.toString(); 
}