使用HttpClient上傳文件,如文件名為中文,會出現(xiàn)中文亂碼問題恰起,解決方法如下:
- 添加上傳格part為UTF-8編碼和瀏覽器兼容格式
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(Charset.forName("UTF-8"));//設(shè)置請求的編碼格式
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//設(shè)置瀏覽器兼容模式
- 表單數(shù)據(jù)設(shè)置編碼
StringBody stringBody = new StringBody("中文亂碼", contentType);
builder.addPart("test", stringBody);
舉例如下:
public boolean uploadFiles(String url, File file, Map<String, String> params) throws Exception {
ContentType contentType = ContentType.create("application/octet-stream", "UTF-8");
HttpClient client = HttpClientBuilder.create().build();// 開啟一個客戶端 HTTP 請求
HttpPost post = new HttpPost(url);//創(chuàng)建 HTTP POST 請求
/// 關(guān)注builder的操作
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(Charset.forName("UTF-8"));//設(shè)置請求的編碼格式
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//設(shè)置瀏覽器兼容模式
builder.addBinaryBody("file", file);
builder.addTextBody("method", params.get("method"));//設(shè)置請求參數(shù)
builder.addTextBody("fileTypes", params.get("fileTypes"));//設(shè)置請求參數(shù)
StringBody stringBody = new StringBody("中文亂碼", contentType);
builder.addPart("test", stringBody);
HttpEntity entity = builder.build();// 生成 HTTP POST 實體
post.setEntity(entity);//設(shè)置請求參數(shù)
HttpResponse response = client.execute(post);// 發(fā)起請求 并返回請求的響應(yīng)
if (response.getStatusLine().getStatusCode() == 200) {
return true;
}
return false;
}