HttpConnection的使用

项目中需要与第三方系统交互,而交互的方式是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());
            }

        }
        

交互很简单 但是细节很重要。。。。

原文地址:https://www.cnblogs.com/lfjjava/p/6093553.html