网站建设佳木斯,网站宣传的方式,wordpress调用产品图片,个人网页设计html论文使用过HttpClient的人都知道可以通过addTextBody方法来添加要上传的文本信息#xff0c;但是#xff0c;如果要上传中文的话#xff0c;或还有中文名称的文件会出现乱码的问题#xff0c;解决办法其实很简单#xff1a; 第一步#xff1a;设置MultipartEntityBuilder的编…使用过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 stringBodynew StringBody(中文乱码,contentType);
builder.addPart(test,stringBody); 附上完整代码 ContentType contentType ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
HttpClient clientnew 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 count0;
for (File file:files) {
// FileBody fileBody new FileBody(file);//把文件转换成流对象FileBody
// builder.addPart(filecount, fileBody);builder.addBinaryBody(filecount, file);count;
}
builder.addTextBody(method, params.get(method));//设置请求参数
builder.addTextBody(fileTypes, params.get(fileTypes));//设置请求参数
StringBody stringBodynew 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; 【原文地址】