在项目中用的HttpClient ,之前没了解过,在使用的过程中出现中文乱码问题,研究了半天都没搞明白。
整个项目都是用的UFT-8编码的。
问题:
/**
*
*parameter 为JSON字符串,含有中文
*/
public static String post(String url, String parameter, Map<String, String> headerMap){
String res = "";
PostMethod method = new PostMethod(url);
//设置header
if(headerMap != null && !headerMap.isEmpty()){
for (String key : headerMap.keySet()) {
method.addRequestHeader(key, headerMap.get(key));
}
}
method.addRequestHeader("Content-Type","application/json;charset=utf-8");
try{
method.setRequestEntity(new StringRequestEntity(parameter));
HttpMethodParams param = method.getParams();
param.setContentCharset("UTF-8");
int state = getHttpClient().executeMethod(method);
if(state == HttpStatus.SC_OK){
res = method.getResponseBodyAsString();
}catch (IOException e) {
e.printStackTrace();
}finally{
//释放连接
method.releaseConnection();
method = null;
}
return res;
}
String res = "";
PostMethod method = new PostMethod(url);
//设置header
if(headerMap != null && !headerMap.isEmpty()){
for (String key : headerMap.keySet()) {
method.addRequestHeader(key, headerMap.get(key));
}
}
method.addRequestHeader("Content-Type","application/json;charset=utf-8");
try{
method.setRequestEntity(new StringRequestEntity(parameter));
HttpMethodParams param = method.getParams();
param.setContentCharset("UTF-8");
int state = getHttpClient().executeMethod(method);
if(state == HttpStatus.SC_OK){
res = method.getResponseBodyAsString();
}catch (IOException e) {
e.printStackTrace();
}finally{
//释放连接
method.releaseConnection();
method = null;
}
return res;
}
在调用post时,出现中文乱码(测试时也很奇葩,parameter包含中文字符少的时候啥问题都没,中文字符多了后就报乱码问题)。
本人通过parameter转码不行,在网上搜了以下两种解决方式,但是都没能解决问题,任然报中文乱码问题!
一、在调用PostMethod方法时设置字符编码:
PostMethod postMethod = new PostMethod(uri);
postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"utf-8");
二、重载PostMethod的getRequestCharSet()方法, 返回我们需要的编码(字符集)名称, 就可以解决 UTF-8 或者其它非默认编码提交 POST 请求时的乱码问题了.
//Inner class for UTF-8 support
public
static
class UTF8PostMethod extends PostMethod{
public UTF8PostMethod(String url){
super(url);
}
@Override
public String getRequestCharSet() {
return "utf-8";
}
}
PostMethod postMethod = new UTF8PostMethod(uri);
后来查RequestEntity 才发现,别人RequestEntity的实现类StringRequestEntity本来就提供
StringRequestEntity(String content) Deprecated. use StringRequestEntity(String, String, String) instead |
StringRequestEntity(String content, String contentType, String charset) Creates a new entity with the given content, content type, and charset. |
解决编码问题的方法。
method.setRequestEntity(new StringRequestEntity(parameter))该为:
method.setRequestEntity(new StringRequestEntity(parameter,"application/json","UTF-8"))问题就解决了。