HttpClient中post get请求http、https示例

使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可:

  • 创建CloseableHttpClient对象。
  • 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
  • 如果需要发送请求参数,可可调用setEntity(HttpEntity entity)方法来设置请求参数。setParams方法已过时(4.4.1版本)。
  • 调用HttpGet、HttpPost对象的setHeader(String name, String value)方法设置header信息,或者调用setHeaders(Header[] headers)设置一组header信息。
  • 调用CloseableHttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个CloseableHttpResponse。
  • 调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容;调用CloseableHttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头。
  • 释放连接。无论执行方法是否成功,都必须释放连接

首先使用maven添加依赖:


      org.apache.httpcomponents
      httpclient
      4.5.3

具体代码如下:

/**
 * @Author: grootdu
 * @Description:
 * @Date: Created in 11:56 2018/11/17
 * @Modified By:
 */
public class HttpClientUtil {

    private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);

    public static String doGet(String url, Map params, Map headers, RequestConfig config) throws Exception{
        String res = "";
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        // 创建uri
        URIBuilder builder = new URIBuilder(url);
        if (params != null) {
            for (String key : params.keySet()) {
                builder.addParameter(key, params.get(key));
            }
        }
        URI uri = builder.build();
        // 创建http GET请求
        HttpGet httpGet = new HttpGet(uri);
//        HttpGet httpGet = new HttpGet(url);//如果url后面带了全部参数的话 也可以直接用这种方式直接创建get请求
        if (headers != null) {
            for (String key : headers.keySet()) {
                httpGet.addHeader(key, headers.get(key));
            }
        }
        try {
            if(config!=null){
                // 构建请求配置信息
//                RequestConfig config = RequestConfig.custom().setConnectTimeout(1000) // 创建连接的最长时间
//                    .setConnectionRequestTimeout(500) // 从连接池中获取到连接的最长时间
//                    .setSocketTimeout(10 * 1000) // 数据传输的最长时间
//                    .setStaleConnectionCheckEnabled(true) // 提交请求前测试连接是否可用
//                    .build();
                httpGet.setConfig(config);
            }
            // 执行请求操作,并拿到结果(同步阻塞)
            response = httpClient.execute(httpGet);
            //获取结果实体
            HttpEntity entity = response.getEntity();
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200 && entity != null) {
                //按指定编码(这里为UTF8编码)转换结果实体为String类型
                res = EntityUtils.toString(entity, "UTF-8");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw e;
        } finally {
            httpGet.releaseConnection();
            try {
                httpClient.close();
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }
        return res;
    }

    public static String doPost(String url, RequestConfig config)  throws Exception {
        return doPost(url, null,config);
    }

    public static String doPost(String url, Map params, RequestConfig config, Map headParams)  throws Exception {
        //对于params中key value,如果是其他类型,比如数组的话,用下面的doPostJson方法更适合,即直接将入参拼成json字符串,JSONObject.toJSONString(map)
        String res = "";
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建Http Post请求对象
        HttpPost httpPost = new HttpPost(url);
        if(headParams != null){
            for(String key : headParams.keySet()){
                httpPost.addHeader(key, headParams.get(key));
            }
        }
        try {
            if(config!=null){
                httpPost.setConfig(config);
            }
            // 创建参数列表
            if (params != null) {
                List paramList = new ArrayList();
                for (String key : params.keySet()) {
                    paramList.add(new BasicNameValuePair(key, params.get(key)));
                }
                // 创建请求内容
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                // 设置参数到请求对象中
                httpPost.setEntity(entity);
            }
            // 执行http请求
            CloseableHttpResponse response = httpClient.execute(httpPost);
            res = EntityUtils.toString(response.getEntity(), "utf-8");
        }  catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw e;
        } finally {
            httpPost.releaseConnection();
            try {
                httpClient.close();
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }
        return res;
    }

    public static String doPostJson(String url, String json, RequestConfig config)  throws Exception {
        String res = "";
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建Http Post请求
        HttpPost httpPost = new HttpPost(url);
        try {
            if (config != null) {
                httpPost.setConfig(config);
            }
            // 设置参数到请求对象中
            httpPost.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON));
            // 执行http请求
            CloseableHttpResponse response = httpClient.execute(httpPost);
            // 获取结果实体
            HttpEntity entity = response.getEntity();
            if(entity != null){
                res = EntityUtils.toString(entity, "utf-8");   
            }
        }   catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw e;
        } finally {
            httpPost.releaseConnection();
            try {
                httpClient.close();
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }
        return res;
    }
    
    public static byte[] doPost(String url, byte[] data) throws Exception {
        byte[] res = null;

        HttpPost httpPost = new HttpPost(url);
        //CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpClient httpClient = HttpClients.custom().disableAutomaticRetries().build();    // disable retry

        try {
            // init post
            /*if (params != null && !params.isEmpty()) {
                List formParams = new ArrayList();
                for (Map.Entry entry : params.entrySet()) {
                    formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
                httpPost.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8"));
            }*/

            // timeout
            RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(10000)
                .setSocketTimeout(10000)
                .setConnectTimeout(10000)
                .build();

            httpPost.setConfig(requestConfig);

            // data
            if (data != null) {
                httpPost.setEntity(new ByteArrayEntity(data, ContentType.DEFAULT_BINARY));
            }
            // do post
            HttpResponse response = httpClient.execute(httpPost);
            // 获取结果实体
            HttpEntity entity = response.getEntity();
            if (null != entity) {
                res = EntityUtils.toByteArray(entity);
                EntityUtils.consume(entity);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw e;
        } finally {
            httpPost.releaseConnection();
            try {
                httpClient.close();
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }
        return res;
    }

    /**
     * read bytes from http request
     * @param request
     * @return
     * @throws IOException
     */
    public static final byte[] readBytes(HttpServletRequest request) throws IOException {
        request.setCharacterEncoding("UTF-8");
        int contentLen = request.getContentLength();
        InputStream is = request.getInputStream();
        if (contentLen > 0) {
            int readLen = 0;
            int readLengthThisTime = 0;
            byte[] message = new byte[contentLen];
            try {
                while (readLen != contentLen) {
                    readLengthThisTime = is.read(message, readLen, contentLen - readLen);
                    if (readLengthThisTime == -1) {
                        break;
                    }
                    readLen += readLengthThisTime;
                }
                return message;
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
                throw e;
            }
        }
        return new byte[] {};
    }
}

对于HTTPS的访问,采取绕过证书的策略:

/**
 * @Author: grootdu
 * @Description:
 * @Date: Created in 16:12 2018/11/14
 * @Modified By:
 */
public class HttpsClientUtil {

    private static Logger logger = LoggerFactory.getLogger(HttpsClientUtil.class);
    /**
     * 绕过验证
     *
     * @return
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     */
    public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
        SSLContext sc = SSLContext.getInstance("SSLv3");

        // 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法
        X509TrustManager trustManager = new X509TrustManager() {
            @Override
            public void checkClientTrusted(
                java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                String paramString) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(
                java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                String paramString) throws CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        sc.init(null, new TrustManager[] { trustManager }, null);
        return sc;
    }

    /**
     * 模拟请求
     *
     * @param url        
     * @param param    
     * @param
     * @return
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     * @throws IOException
     * @throws ClientProtocolException
     */
    public static String doGet(String url, Map param, RequestConfig config) throws Exception {
        String res = "";
        //采用绕过验证的方式处理https请求
        SSLContext sslcontext = createIgnoreVerifySSL();
        // 设置协议http和https对应的处理socket链接工厂的对象
        Registry socketFactoryRegistry = RegistryBuilder.create()
            .register("http", PlainConnectionSocketFactory.INSTANCE)
            .register("https", new SSLConnectionSocketFactory(sslcontext))
            .build();
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        //创建自定义的httpclient对象
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connManager).build();
        // 创建uri
        URIBuilder builder = new URIBuilder(url);
        if (param != null) {
            for (String key : param.keySet()) {
                builder.addParameter(key, param.get(key));
            }
        }
        URI uri = builder.build();
        // 创建http GET请求
        HttpGet httpGet = new HttpGet(uri);
        try {
            if(config!=null){
                httpGet.setConfig(config);
            }
            // 执行请求
            CloseableHttpResponse response = httpClient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                res = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw e;
        } finally {
            httpGet.releaseConnection();
            try {
                httpClient.close();
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }
        return res;
    }
}

参考博客:
https://www.cnblogs.com/Mr-Rocker/p/6229652.html
https://www.cnblogs.com/moy25/p/8658762.html
https://www.656463.com/article/httpclientqingqiucanshushezhi_8

你可能感兴趣的:(HttpClient中post get请求http、https示例)