2011-02-09 179 views
5

未在android中獲取http發佈請求的響應正文。
我提的是在名稱值對的用戶ID,密碼和由在android中沒有得到http post請求的響應正文?

postrequest.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

把在httppost請求,但上執行我得到的響應爲SC_OK(200),但反應體是null

另外一個問題是,如果我使用setHeader()函數指定HTTPGet或HTTPPost請求中的頭文件,我將得到BAD REQUEST(404)響應。

請幫我解決上述問題。

感謝&問候,
SSuman185

+1

把你的代碼調用,並閱讀響應。 – Aliostad 2011-02-09 13:18:49

+1

您是否確認服務器實際發送了回覆? – sstn 2011-02-12 17:37:37

回答

0

喜的朋友PL嘗試這種方式來獲得服務器響應..

如果給定鏈路是其中u要發佈請求的鏈接..

String link2 = "http://184.106.227.45/quaddeals/university-of-illinois/androids_deals/user_card_list.json"; 

DefaultHttpClient hc1 = new DefaultHttpClient(); 

ResponseHandler<String> res1 = new BasicResponseHandler(); 

HttpPost postMethod1 = new HttpPost(link2); 

List<NameValuePair> nameValuePairs1 = new ArrayList<NameValuePair>(1); 

nameValuePairs1.add(new BasicNameValuePair("user_id",account_userId)); 

postMethod1.setEntity(new UrlEncodedFormEntity(nameValuePairs1)); 

String response1 = hc1.execute(postMethod1, res1); 
1

這裏有一個方法可以輕鬆POST到頁面,並以字符串形式獲取響應。第一個參數(HashMap)是您想要發送的參數的鍵值列表。沒有錯誤處理,所以你必須這樣做:

public static String doPost(HashMap<String,String> params, String url) { 
     HttpPost httpost = new HttpPost(url); 
     try { 
      httpost.setURI(new URI(url)); 
     } catch (URISyntaxException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } 
     HttpResponse response = null; 

     List <NameValuePair> nvps = new ArrayList <NameValuePair>(); 

     Set entryset = params.entrySet(); 
     Iterator iterator = entryset.iterator(); 
     Log.d("Posted URL: ", url+" "); 
     while(iterator.hasNext()) { 
      Map.Entry mapentry = (Map.Entry)iterator.next(); 
      String key = ((String)mapentry.getKey()).toString(); 
      String value = (String)mapentry.getValue(); 
      nvps.add(new BasicNameValuePair(key, value)); 

      Log.d("Posted param: ", key+" = "+value); 
     } 

     try { 
      httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); 
      try { 
       httpost.setURI(new URI(url)); 
      } catch (URISyntaxException e1) { 
       // TODO Auto-generated catch block 
       e1.printStackTrace(); 
      } 
      response = getClient().execute(httpost); 
      HttpEntity entity = response.getEntity(); 

      return convertStreamToString(entity.getContent()); 
     } catch (Exception e) { 
      // some connection error occurred, nothing we can do 
      e.printStackTrace(); 
     } 

     return null; 
    }