说明:使用的httpClient version 为4.3.6
最近写一个项目,需要上传附件,发现后台解析时中文是乱码,一开始以为是字符编码问题,网上差了n多资料,没解决问题,折腾了1天,终于搞定问题,直接上代码。
public class UpLoadDemo { @Test public void testImport() { File file1 = new File("C:\\Users\\Thinkpad\\Desktop\\pics\\测试1.jpg"); File file2 = new File("C:\\Users\\Thinkpad\\Desktop\\pics\\测试2.jpg"); List fileList = new ArrayList<>();
fileList.add(file1);
fileList.add(file2);
CloseableHttpClient client = HttpClients.createDefault();
String responseContent = null; // 响应内容
CloseableHttpResponse response = null;
String uploadurl =
"http://localhost:8081/id-shadow/id-shadow/1.0/bucketUser/bucketDataImport" +
"/bucketCode/5a55e4848922304e98c4b5ec/block_id/1233/partnerCode/201608304777/outOrderId/" + System.currentTimeMillis();
HttpPost post = new HttpPost(uploadurl);
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
// multipartEntityBuilder.setCharset(Charset.forName(HTTP.UTF_8));
//设置请求的编码格式,填坑,遇到乱码时,第一错觉就是设置请求的编码格式,如果设置这个编码,会导致多文件丢失(具体原因不明)
// multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
//设置浏览器兼容模式 ,填坑,网上好多文章说,设置成BOWSER_COMPATIBLE 就不会乱码了,问题就出现在这里,设置模式时,应该设置成HttpMultipartMode.RFC6532 才没有出现乱码
try {
for (int i = 0;i< fileList.size();i++) {
File file = fileList.get(i);
multipartEntityBuilder.addBinaryBody("file" + i,file);
}
HttpEntity reqEntity = multipartEntityBuilder.build();
post.setEntity(reqEntity);
response = client.execute(post);
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
responseContent = EntityUtils.toString(entity, "UTF-8");
JSONObject object = JSONObject.parseObject(responseContent);
System.out.print(responseContent);
boolean isSuccess = object.getJSONObject("result").getBoolean("success");
if (isSuccess) {
JSONArray arr = object.getJSONArray("data");
// todo 内部逻辑实现
// doSomething()
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null)
response.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (client != null)
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
网友评论