Java利用原始HttpURLConnection发送http请求数据小结

1,在post请求下,写输出应该在读取之后,否则会抛出异常。

即操作OutputStream对象应该在InputStreamReader之前。

2.conn.getResponseCode()获取返回状态码最好放在读写完成之后,否则也会抛出异常。这里不知道是否是该方法会导致连接关闭,待验证。

下面贴出工具类代码

其中GET请求直接在requestUrl里面拼接,POST请求通过outputStr传入。

/**
     * 发送https请求
     * @param requestUrl 请求地址
     * @param requestMethod 请求方式(GET、POST)
     * @param outputStr 提交的数据
     * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
     */
    public static WxApiResult httpsRequest(String requestUrl, String requestMethod, String outputStr) {
        WxApiResult message = new WxApiResult();
        try{
            TrustManager[] tm = { new MyX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(requestUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setSSLSocketFactory(ssf);

            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod(requestMethod);

            if(null != outputStr){
                OutputStream outputStream = conn.getOutputStream();
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null){
                buffer.append(str);
            }
            if(conn.getResponseCode() == conn.HTTP_OK){
                message.setCode(0);
                message.setContent(buffer.toString());
            }else{
                message.setCode(-1);
                message.setContent("获取返回状态不对,返回状态为:" + conn.getResponseCode());
            }

            // 释放资源
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            conn.disconnect();

        }catch (ConnectException ce){
            log.error("连接超时:{}", ce);
            message.setCode(-1);
            message.setContent(ce.getMessage());
        }catch (Exception e){
            log.error("https请求异常:{}", e);
            message.setCode(-1);
            message.setContent(e.getMessage());
        }
        return message;
    }

 

 

 

 

posted @ 2017-10-26 14:15  .Oneday  阅读(1849)  评论(0编辑  收藏  举报