文章 96
评论 76
浏览 89991
org.apache.http工具类使用

org.apache.http工具类使用

Maven 的 pom 引入:

<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>4.5.7</version>
</dependency>

依赖的 jar 文件:

jar包依赖.png

GET 方法:

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public static String get(String url) throws Exception{
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response2 = HttpClients.createDefault().execute(httpGet);

        try {

            response2.getStatusLine().getStatusCode();//HttpStatus.SC_OK

            HttpEntity entity2 = response2.getEntity();
            String response=EntityUtils.toString(entity2,"utf-8");//返回报文

            EntityUtils.consume(entity2);//关闭资源
            return response;
        } finally {
            response2.close();//关闭资源
        }
    }

POST 方法访问 http:

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public static String post(String url,String json) throws Exception{

        StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);//设置消息头 Content-Type application/json; charset=UTF-8
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(entity);
        CloseableHttpResponse response2 = HttpClients.createDefault().execute(httpPost);

        try {

            response2.getStatusLine().getStatusCode();//HttpStatus.SC_OK

            HttpEntity entity2 = response2.getEntity();
            String response=EntityUtils.toString(entity2,"utf-8");//返回报文

            EntityUtils.consume(entity2);//关闭资源
            return response;
        } finally {
            response2.close();//关闭资源
        }
    }

POST 方法访问 https:

去除 ssl 验证
package com.ulane.spring.util;

/**
 * @author Xu Yuntong
 * @date 2019/11/26 10:49
 */
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;

public class HttpsClientUtil {

    private static CloseableHttpClient httpClient;

    static {
        try {
            SSLContext sslContext = SSLContextBuilder.create().useProtocol(SSLConnectionSocketFactory.SSL).loadTrustMaterial((x, y) -> true).build();
            RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).setSocketTimeout(5000).build();
            httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).setSSLContext(sslContext).setSSLHostnameVerifier((x, y) -> true).build();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String doPost(String url, String jsonString) {
        try {
            HttpPost httpPost = new HttpPost(url);
            StringEntity stringEntity = new StringEntity(jsonString, "utf-8");
            stringEntity.setContentType("application/json");
            httpPost.setEntity(stringEntity);
            CloseableHttpResponse response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                httpPost.abort();
                throw new RuntimeException("HttpClient,error status code :"
                        + statusCode);
            }
            HttpEntity entity = response.getEntity();
            String result = null;
            if (entity != null) {
                result = EntityUtils.toString(entity, "utf-8");
            }
            EntityUtils.consume(entity);
            response.close();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}


记录精彩的坎坷人生,经营属于自己的世界!