httpClient使用postMethod方法傳送請求,攜帶引數並解決中文亂碼問題
阿新 • • 發佈:2019-02-02
前言:工作中遇到兩個系統之間通訊的問題,需求是這樣的:要求將資訊上報給上級部門(這裡的上級部門是兩一個系統),這就是跨系統通訊了
解決方案:使用httpclient實現網路通訊,傳遞資料。
關鍵問題:httpClient postMethod 傳遞引數 防止中文亂碼
一,所需jar包
maven引用如下:
<dependency> <groupId>commons-httpclient</groupId> <artifactId>commons-httpclient</artifactId> <version>3.0</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.3</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging-api</artifactId> <version>1.1</version> </dependency>
二,使用httpclient的postMethod方法傳送請求:
//建立PostMethod的子類設定編碼格式 public static class UTF8PostMethod extends PostMethod{ public UTF8PostMethod(String url){ super(url); } @Override public String getRequestCharSet() { //return super.getRequestCharSet(); return "UTF-8"; } }
上面的程式碼都有備註。JSONObject json = JSONObject.fromObject(event);//將java物件轉換為json物件 String str = json.toString();//將json物件轉換為字串 String url = "http://172.20.57.87:8080/gyly_ec_new3/api/mobileservices/district";//介面url HttpClient client = new HttpClient();//建立httpClient物件 PostMethod post = new UTF8PostMethod(url);//建立PostMethod的子類UTF8PostMethod來設定編碼 NameValuePair message = new NameValuePair("json", str);//post請求必須使用 NameValuePair 類傳遞引數 post.setRequestBody(new NameValuePair[]{message}); try { int code=client.executeMethod(post);//傳送資料 if (code==200) { System.out.println("請求成功!"); }else { System.out.println("請求失敗!"); } } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { post.releaseConnection();//關閉連線 }
主要說一下:
PostMethod post = new UTF8PostMethod(url);//建立PostMethod的子類UTF8PostMethod來設定編碼
這裡使用postMethod 物件,防止中文亂碼,必須建立其子類UTF8PostMethod
設定編碼,才可以防止中文亂碼。
結語:在網上看了很多種httpclient的用法,自己在做的時候也遇到很多問題,現在問題解決了,寫部落格的時候卻感覺沒什麼可寫的,關鍵是找到正確的方式。如上程式碼中我已經實現,並且可以使用。
如果你恰好也有同樣的需求,在看了我的程式碼後有不明白的地方,可以給我留言,或者加我的qq:416404891,我會盡力給你解答。
互相學習。。。。。。。。。。。。。。。。。。
晚安!