Android设置内容类型HttpPost
你怎么能改变Android中的HttpPost的内容类型?
对于一个请求,我需要将内容类型设置为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);
但这并不能解决问题,我无法在任何地方找到解决方案。
干杯
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<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();
}
链接地址: http://www.djcxy.com/p/50953.html