使用HttpClient上傳文件,如文件名為中文,會出現中文亂碼問題,解決方法如下:
- 添加上傳格part為UTF-8編碼和瀏覽器兼容格式
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(Charset.forName("UTF-8"));//設置請求的編碼格式
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//設置瀏覽器兼容模式
- 表單數據設置編碼
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);//創建 HTTP POST 請求
/// 關注builder的操作
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(Charset.forName("UTF-8"));//設置請求的編碼格式
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//設置瀏覽器兼容模式
builder.addBinaryBody("file", file);
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;
}