項目中需要與第三方系統交互,而交互的方式是XML報文形式,所以會用到HttpConnection與第三方系統連接交互,使用起來並不復雜,但是有幾點需要注意的:
1.亂碼的問題解決
2.超時的設置,注意這個問題很嚴重,當你網絡正常的時候看不出區別,但是當你網絡不正常的時候,沒有設置超時時間會導致你的系統一直嘗試連接三方系統,可能會導致系統延遲很久所以一定記得處理,一個應用的效率很重要。
附上代碼:
HttpURLConnection urlConnection = null; OutputStream outputStream = null; BufferedReader bufferedReader = null; try { URL httpUrl = new URL(url);//創建對應的url對象 urlConnection = (HttpURLConnection) httpUrl.openConnection();//HttpConnection對象,這一步只是創建了對象並沒有連接遠程服務器 urlConnection.setDoInput(true);//允許讀 urlConnection.setDoOutput(true);//允許寫 urlConnection.setRequestMethod("POST");//請求方式 urlConnection.setRequestProperty("Pragma:", "no-cache"); urlConnection.setRequestProperty("Cache-Control", "no-cache"); urlConnection.setRequestProperty("Content-Type", "text/xml");//請求的消息格式 urlConnection.setConnectTimeout(6000);//很重要,設置超時時間 urlConnection.connect();//真正的連接服務器 outputStream = urlConnection.getOutputStream(); byte[] bytes = xml.getBytes("GBK");//這里的xml即為你想傳遞的值,因為項目中與三方交互要用GBK編碼所以轉換為GBK outputStream.write(bytes);//傳遞值 StringBuffer temp = new StringBuffer(); InputStream in = new BufferedInputStream(urlConnection.getInputStream()); Reader rd = new InputStreamReader(in,"GBK");//服務器返回的也是GBK編碼格式的數據。 int c = 0; while ((c = rd.read()) != -1) { temp.append((char) c); }//其實可以使用String str =new String(response.getBytes(),"GBK");這種方式解決亂碼問題,但是這次項目中使用這種方式並沒有解決,所以干脆一個個字節的轉。 in.close(); return temp.toString(); } catch (MalformedURLException e) { log.error("connect server failed,cause{}", e.getMessage()); } catch (IOException e) { log.error("io execute failed,cause{}", e.getMessage()); throw e; } finally { try { if (!Arguments.isNull(outputStream)) { outputStream.close(); } if (!Arguments.isNull(bufferedReader)) { bufferedReader.close(); } //該處理的資源需要處理掉,該關閉的需要關閉 } catch (IOException e) { log.error("io close failed , cause{}", e.getMessage()); } }
交互很簡單 但是細節很重要。。。。