httpclient post中文乱码问题的解决方案
原文链接:http://www.zihou.me/2009/04/13/304
这两天用到了HttpClient来模拟Form表单的Post提交,提交的过程倒还顺利,没有问题,但提交后发现了一个java里非常常见的中文乱码问题.
后来在google里搜httpclient post中文乱码,找到了一位朋友贴出的解决方法,说是要重载EntityEnclosingMethod.java类里的getRequestCharSet()方法,如下:
public static class UTF8PostMethod extends PostMethod{
public UTF8PostMethod(String url){
super(url);
}
@Override
public String getRequestCharSet() {
//return super.getRequestCharSet();
return “UTF-8″;
}
}
但可能是版本不一致的原因(我用的3.1版本,而这位朋友是对3.0版本说的),试了下还是不行,于是只好自己去查看源代码,后来发现了解决方法,模拟POST的代码如下:
PostMethod filePost = new PostMethod(targetURL);
try {
Part[] parts = {new StringPart(“name”, “测试test”),new FilePart(“file”, f)};
filePost.setRequestEntity(
new MultipartRequestEntity(parts, filePost.getParams())
);
HttpClient client = new HttpClient();
client.getHttpConnectionManager().
getParams().setConnectionTimeout(5000);
int status = client.executeMethod(filePost);
if (status == HttpStatus.SC_OK) {
System.out.println(
“Upload complete, response=” + filePost.getResponseBodyAsString()
);
} else {
System.out.println(
“Upload failed, response=” + HttpStatus.getStatusText(status)
);
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
filePost.releaseConnection();
}
因为是”测试test”为乱码,所以查看类StringPart
public StringPart(String name, String value, String charset) {
super(
name,
DEFAULT_CONTENT_TYPE,
charset == null ? DEFAULT_CHARSET : charset,
DEFAULT_TRANSFER_ENCODING
);
if (value == null) {
throw new IllegalArgumentException(“Value may not be null”);
}
if (value.indexOf(0) != -1) {
// See RFC 2048, 2.8. “8bit Data”
throw new IllegalArgumentException(“NULs may not be present in string parts”);
}
this.value = value;
}
发现还有第三个参数字符集charset,如果传入了就以传入的为准,否则就会默认一个字符集,这个默认的字符集就是乱码的根源所在,所以将以上的
Part[] parts = {new StringPart(“name”, “测试test”),new FilePart(“file”, f)};
改为
Part[] parts = {new StringPart(“name”, “测试test”,”GBK”),new FilePart(“file”, f)};
再次运行,中文乱码就不见了。。。
注:字符集得根据具体情况来定,比如你要提交的页面字符集为GBK,那么这里就是GBK,如果是“UTF-8”,则为UTF-8;另外这个问题是针对httpClient3.1版本来说的,对其他版本可能不一定适用。
非转载说明,本博文章皆为原创,转载本博文章请务必注明文章出处:
转载自子猴博客
本文链接地址: httpclient post中文乱码问题的解决方案

我看到流量统计中有搜类似:”httpClient抓取带中文参数的链接”到此页面的,这个在此也说一下,有种处理方法是将这些中文参数进行编码(URLEncoder或base64均可)转换一下(或者对整个链接进行编码)