處理httpClient上傳附件時 附件名中文亂碼問題


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();
}
}

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM