使用過HttpClient的人都知道可以通過addTextBody方法來添加要上傳的文本信息,但是,如果要上傳中文的話,或還有中文名稱的文件會出現亂碼的問題,解決辦法其實很簡單:
第一步:設置MultipartEntityBuilder的編碼方式為UTF-8。
builder.setCharset(Charset.forName(HTTP.UTF_8));//設置請求的編碼格式
第二步:創建ContentType對象,指定UTF-8編碼。
ContentType contentType= ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
第三步:使用addPart+?StringBody代替addTextBody。如:
StringBody stringBody=new StringBody("中文亂碼",contentType); builder.addPart("test",stringBody);
附上完整代碼:
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;
【原文地址】