最近开发微信公众号平台时,需要使用到HTTP请求发送的方法,所以撸了两种出来

  • 使用原生HttpURLConnection
public class HttpClientTest {
    /**
     * Get请求
     * @param httpUrl
     * @return
     * @throws IOException
     */
    public static String doGet(String httpUrl) throws IOException {
        //1.创建HttpURLConnection对象 2.创建输入流对象 3.创建url对象,打开连接 4.设置连接属性 5.发送请求 6.获取输入流,封装字符集
        //7.存放数据 8.关闭资源和连接
        URL url = null;
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod(\"GET\");
        connection.setReadTimeout(1000);
        connection.connect();
        InputStream inputStream = connection.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
        StringBuilder stringBuilder = new StringBuilder();
        while (bufferedReader.readLine() != null) {
            stringBuilder.append(bufferedReader.readLine());
            stringBuilder.append(\"\\r\\n\");
        }
        bufferedReader.close();
        connection.disconnect();
        return stringBuilder.toString();
    }

    /**
     * Post请求
     * @param httpUrl
     * @param param
     * @return
     * @throws IOException
     */
    public static String doPost(String httpUrl, String param) throws IOException {
        //1.创建连接、输入输出、字符集对象 2.打开连接,设置属性 3.通过连接对象获取输出流 4.通过输出流写数据
        //5.获取连接对象到的输入流,拿到返回数据 6.关闭资源
        URL url = null;
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod(\"POST\");
        connection.setDoOutput(true);
        OutputStream out = connection.getOutputStream();
        out.write(param.getBytes());
        InputStream in = connection.getInputStream();
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
        while (bufferedReader.readLine() != null) {
            stringBuilder.append(bufferedReader.readLine());
            stringBuilder.append(\"\\r\\n\");
        }
        bufferedReader.close();
        connection.disconnect();
        return stringBuilder.toString();
    }

}
  • 使用HttpClient工具,注意这里是4.5版本,不同版本API差别巨大
public class HttpClientTest1 {
    /**
     * Get请求
     *
     * @param httpUrl
     * @return
     * @throws IOException
     */
    public static String doGet(String httpUrl) throws IOException {
        //1.创建httpClient,httpGet对象 2.配置请求信息 3.执行get请求,通过httpEntity对象得到返回数据 4.字符转换
        //5.关闭资源
        String result;
        //两种创建client的方法,这里是使用了CloseableHttpClient这个实现类,相当于已经废弃的defaultHttpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(httpUrl);
        //根据实际配置,这里是默认配置,超时设置连接设置什么的都是通过RequestConfig对象配置的
        httpGet.setConfig(RequestConfig.DEFAULT);
        CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
        HttpEntity httpEntity = httpResponse.getEntity();
        result = EntityUtils.toString(httpEntity);
        httpResponse.close();
        return result;

    }

    /**
     * Post请求
     *
     * @param httpUrl
     * @param param
     * @return
     * @throws IOException
     */
    public static String doPost(String httpUrl, String param) throws IOException {
        //1.创建httpClient,httpPost对象 2.配置请求信息 3.执行post请求 4.获得httpEntity,进行字符转换 5.关闭资源
        String result;
        //这里使用HttpClient创建client,使用面向接口编程
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost();
        httpPost.setConfig(RequestConfig.DEFAULT);
        httpPost.setEntity(new StringEntity(param));
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        result = EntityUtils.toString(httpEntity);
        return result;
    }

}

在第二种使用HttpClientBuiler的方式中,没有进行上面的释放资源的操作,是因为通过HttpClientBuiler的build方法创建出来的对象,包含了Closeable对象,Closeable对象继承了AutoCloseable对象,源码如下


        List<Closeable> closeablesCopy = closeables != null ? new ArrayList<Closeable>(closeables) : null;
        if (!this.connManagerShared) {
            if (closeablesCopy == null) {
                closeablesCopy = new ArrayList<Closeable>(1);
            }
            final HttpClientConnectionManager cm = connManagerCopy;

            if (evictExpiredConnections || evictIdleConnections) {
                final IdleConnectionEvictor connectionEvictor = new IdleConnectionEvictor(cm,
                        maxIdleTime > 0 ? maxIdleTime : 10, maxIdleTimeUnit != null ? maxIdleTimeUnit : TimeUnit.SECONDS,
                        maxIdleTime, maxIdleTimeUnit);
                closeablesCopy.add(new Closeable() {

                    @Override
                    public void close() throws IOException {
                        connectionEvictor.shutdown();
                        try {
                            connectionEvictor.awaitTermination(1L, TimeUnit.SECONDS);
                        } catch (final InterruptedException interrupted) {
                            Thread.currentThread().interrupt();
                        }
                    }

                });
                connectionEvictor.start();
            }
            closeablesCopy.add(new Closeable() {

                @Override
                public void close() throws IOException {
                    cm.shutdown();
                }

            });
        }

        return new InternalHttpClient(
                execChain,
                connManagerCopy,
                routePlannerCopy,
                cookieSpecRegistryCopy,
                authSchemeRegistryCopy,
                defaultCookieStore,
                defaultCredentialsProvider,
                defaultRequestConfig != null ? defaultRequestConfig : RequestConfig.DEFAULT,
                closeablesCopy);
    }

 

收藏 打印