关于HttpClient上传中文乱码的解决办法

使用过HttpClient的人都知道可以通过addTextBody方法来添加要上传的文本信息,但是,如果要上传中文的话,或还有中文名称的文件会出现乱码的问题,解决办法其实很简单:

第一步:设置MultipartEntityBuilder的编码方式为UTF-8。

builder.setCharset(Charset.forName(HTTP.UTF_8));//设置请求的编码格式

第二步:创建ContentType对象,指定UTF-8编码。

ContentType contentType= ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);

第三步:使用addPart+ StringBody代替addTextBody。如:

**StringBody stringBody=new StringBody(“中文乱码”,contentType);
builder.addPart(“test”,stringBody);**

附上完整代码:
**ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
HttpClient client=new DefaultHttpClient();// 开启一个客户端 HTTP 请求
HttpPost post = new HttpPost(url);//创建 HTTP POST 请求
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(Charset.forName(HTTP.UTF_8));//设置请求的编码格式
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//设置浏览器兼容模式
int count=0;
for (File file:files) {
// FileBody fileBody = new FileBody(file);//把文件转换成流对象FileBody
// builder.addPart(“file”+count, fileBody);
builder.addBinaryBody(“file”+count, file);
count++;
}
builder.addTextBody(“method”, params.get(“method”));//设置请求参数
builder.addTextBody(“fileTypes”, params.get(“fileTypes”));//设置请求参数
StringBody stringBody=new StringBody(“中文乱码”,contentType);
builder.addPart(“test”, stringBody);
HttpEntity entity = builder.build();// 生成 HTTP POST 实体
post.setEntity(entity);//设置请求参数
HttpResponse response = client.execute(post);// 发起请求 并返回请求的响应
if (response.getStatusLine().getStatusCode()==200) {
return true;
}
return false;**

原文地址:http://www.itnose.net/detail/6144587.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值