關於HttpClient上傳中文亂碼的解決辦法

使用過HttpClient的人都知道能夠經過addTextBody方法來添加要上傳的文本信息,可是,若是要上傳中文的話,或還有中文名稱的文件會出現亂碼的問題,解決辦法其實很簡單:瀏覽器

第一步:設置MultipartEntityBuilder的編碼方式爲UTF-8。post

builder.setCharset(Charset.forName(HTTP.UTF_8));//設置請求的編碼格式 

第二步:建立ContentType對象,指定UTF-8編碼。ui

ContentType contentType= ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8); 

第三步:使用addPart+ StringBody代替addTextBody。如:編碼

StringBody stringBody=new StringBody("中文亂碼",contentType);
builder.addPart("test",stringBody);

附上完整代碼:url

ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);      
HttpClient client=new DefaultHttpClient();// 開啓一個客戶端 HTTP 請求 
HttpPost post = new HttpPost(url);//建立 HTTP POST 請求  
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(Charset.forName(HTTP.UTF_8));//設置請求的編碼格式
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//設置瀏覽器兼容模式
int count=0;
for (File file:files) {
//            FileBody fileBody = new FileBody(file);//把文件轉換成流對象FileBody
//            builder.addPart("file"+count, fileBody);
    builder.addBinaryBody("file"+count, file);
    count++;
}        
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;

原文地址spa

相關文章
相關標籤/搜索