Android设置内容types为HttpPost

如何在android中更改HttpPost的内容types

对于请求,我需要将内容types设置为application / x-www-form-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); 

但这并没有成功,我无法在任何地方find解决方案。

干杯

Solutions Collecting From Web of "Android设置内容types为HttpPost"

  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对。

不推荐使用: nameValuePairs

替代方案:使用volley library

电话的完整代码,适用于任何可能需要它的人。

  List nameValuePairs = new ArrayList(); 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(); }