Goo*_*oey 22 encoding android content-type header http-post
如何在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);
Run Code Online (Sandbox Code Playgroud)
但这并没有成功,我无法在任何地方找到解决方案.
干杯
wts*_*g02 43
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);
Run Code Online (Sandbox Code Playgroud)
注意:构建器只包含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();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
40778 次 |
| 最近记录: |