2013-03-25 70 views
21

如何在Android中更改HttpPost的內容類型?Android設置內容類型HttpPost

因爲我需要設置內容類型應用程序/ x-WWW窗體-urlencoded

所以我得到了這段代碼的請求:

httpclient=new DefaultHttpClient(); 
httppost= new HttpPost(url); 
StringEntity se = new StringEntity(""); 
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded")); 
httppost.setEntity(se); 

但是,這並不做技巧,我無法在任何地方找到解決方案。

乾杯

回答

41
  HttpPost httppost = new HttpPost(builder.getUrl()); 
      httppost.setHeader(HTTP.CONTENT_TYPE, 
        "application/x-www-form-urlencoded;charset=UTF-8"); 
      // Add your data 
      httppost.setEntity(new UrlEncodedFormEntity(builder 
        .getNameValuePairs(), "UTF-8")); 

      // Execute HTTP Post Request 
      HttpResponse response = httpclient.execute(httppost); 

注:製造商只包含URL和namevalue對。

+0

由於表單也是身份驗證請求,我已經設置了另一個頭。這不會重寫嗎? – Gooey

+0

明白了一切工作,謝謝! (頭不會被覆蓋)。 – Gooey

+0

非常感謝您節省了一天的時間 –

7

已過時:nameValuePairs

替代方案:用volley library

的完整代碼調用,對於誰可能需要它。

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
    nameValuePairs.add(new BasicNameValuePair("grant_type", "password")); 
    nameValuePairs.add(new BasicNameValuePair("username", "user1")); 
    nameValuePairs.add(new BasicNameValuePair("password", "password1")); 

    HttpClient httpclient=new DefaultHttpClient(); 
    HttpPost httppost = new HttpPost("www.yourUrl.com"); 
    httppost.setHeader(HTTP.CONTENT_TYPE,"application/x-www-form-urlencoded;charset=UTF-8"); 

    try { 
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8")); 
    } catch (UnsupportedEncodingException e) { 
     e.printStackTrace(); 
    } 

    // Execute HTTP Post Request 
    try { 
     HttpResponse response = httpclient.execute(httppost); 
     Log.d("Response:" , response.toString()); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
+1

nameValuePairs已棄用。你能用Map或HashMap編輯你的代碼片段嗎? –

+0

好點,我沒有在atm項目上工作,如果你,@AnandSavjani正在處理它,並找到一個更新的方式與地圖,請編輯響應; 10x – msysmilu

+1

我已經解決了我的問題,它支持所有類型的方法和內容類型:) –