左右HttpClient上傳的方法來解決中國的亂碼

2021-09-07 02:37:59 字數 1605 閱讀 3390

二手httpclient人們都知道通過addtextbody方法來加入要上傳的文字資訊,可是,假設要上傳中文的話。或還有中文名稱的檔案會出現亂碼的問題,解決的方法事實上非常easy:

第一步:設定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);

附上完整**:

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)

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 false;

httpclient 上傳檔案

3.0版本 用multipartrequestentity方式,怎麼搞都不行。最後還是用了multipartpostmethod,才算搞定 總之,不好使啊.具體使用方式如下 2,post.addrequestheader content type multipart form data charse...

HttpClient上傳檔案

httpclient post請求 上傳多 檔案 param url 請求位址 param params 引數列表 return 響應字串 throws unsupportedencodingexception author jie date 2015 2 12 public static stri...

使用httpclient上傳檔案

由於客戶端有上傳檔案的需求,伺服器接收到客戶端上傳的檔案後,需要將檔案透傳給後台業務系統.以前給後台業務系統互動時,組裝多段請求時使用的是org.apache.http.entity.mime.content.filebody物件儲存檔案物件透傳,但是這樣的話,伺服器需要在本地生成臨時檔案,比較麻煩...