HttpClient 4.3.* 上傳帶中文文件名文件文件名亂碼問題的解決

又是折騰了一天才解決的問題,網上關於這個問題的資料很少,但願寫出來能幫到有須要的人。java

以前不管怎麼設置charset都不起做用,apache

後來看了這篇文章 才發現MultipartEntityBuilder有一個setMode的方法瀏覽器

能夠設置成以瀏覽器兼容模式運行,設置後便不會亂碼了。測試

下面是測試的源碼:ui

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.CharsetUtils;
import org.apache.http.util.EntityUtils;

public class FileUploadTest {

    /**
     * 這個例子展現瞭如何執行請求包含一個多部分編碼的實體 模擬表單提交
     * 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        
        try {
            // 要上傳的文件的路徑
            String filePath = new String("D:\\吹風.gif");
            // 把一個普通參數和文件上傳給下面這個地址 是一個servlet
            HttpPost httpPost = new HttpPost(
                    "http://localhost:8080/abc/updateUserBgImg");
            // 把文件轉換成流對象FileBody
            File file = new File(filePath);
            FileBody bin = new FileBody(file);  
            StringBody userId = new StringBody(
                    "用戶ID", ContentType.create(
                            "text/plain", Consts.UTF_8));
//以瀏覽器兼容模式運行,防止文件名亂碼。   HttpEntity reqEntity
= MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE) .addPart("multipartFile", bin) .addPart("userId", userId).setCharset(CharsetUtils.get("UTF-8")).build(); httpPost.setEntity(reqEntity); System.out.println("發起請求的頁面地址 " + httpPost.getRequestLine()); // 發起請求 並返回請求的響應 CloseableHttpResponse response = httpClient.execute(httpPost); try { System.out.println("----------------------------------------"); // 打印響應狀態 System.out.println(response.getStatusLine()); // 獲取響應對象 HttpEntity resEntity = response.getEntity(); if (resEntity != null) { // 打印響應長度 System.out.println("Response content length: " + resEntity.getContentLength()); // 打印響應內容 System.out.println(EntityUtils.toString(resEntity, Charset.forName("UTF-8"))); } // 銷燬 EntityUtils.consume(resEntity); } finally { response.close(); } } finally { httpClient.close(); } } }
相關文章
相關標籤/搜索