HttpConnection的使用

項目中須要與第三方系統交互,而交互的方式是XML報文形式,因此會用到HttpConnection與第三方系統鏈接交互,使用起來並不複雜,可是有幾點須要注意的:服務器

1.亂碼的問題解決網絡

2.超時的設置,注意這個問題很嚴重,當你網絡正常的時候看不出區別,可是當你網絡不正常的時候,沒有設置超時時間會致使你的系統一直嘗試鏈接三方系統,可能會致使系統延遲好久因此必定記得處理,一個應用的效率很重要。app

附上代碼:編碼

        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());
            }

        }
        

交互很簡單 可是細節很重要。。。。url

相關文章
相關標籤/搜索