Java uses the org.apache.http package to access the URL address of the other party and send data (not OkHttp)

Java uses the org.apache.http package to access the URL address of the other party and send data (not OkHttp).
For the URL of the https protocol, skip the verification access directly


import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.net.ConnectException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;


public class NetworkUtils {
    
    
//发送Get请求
    public static JSONObject doGetByHttpClient(String url) throws ConnectException {
    
    
        System.out.println("url =" + url);

        try {
    
    
        //如果是https 用这种方式
            CloseableHttpClient httpClient = null;
            if (url.toLowerCase().startsWith("https://")) {
    
    
                System.out.println("use ssl");
                httpClient = getHttpsClient();
            } else {
    
    
            //如果是http 用这种方式
                System.out.println("use nonssl");
                httpClient = HttpClients.createDefault();
            }

            HttpGet httpGet = new HttpGet(url);
            httpGet.addHeader("Content-Type", "application/json; charset=UTF-8");

            HttpResponse response = httpClient.execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
    
    
                throw new ConnectException("连接服务器失败!");
            }
            String s = EntityUtils.toString(response.getEntity());
            JSONObject json = JSONObject.parseObject(s);
            return json;
        } catch (Exception e) {
    
    
            e.printStackTrace();
            System.out.println(" ===== doPostByHttpClient() ERROR ===== ");
            throw new ConnectException(e.getMessage());
        } finally {
    
    
            System.clearProperty("javax.net.debug");
        }

    }

    //发送Post请求
    public static JSONObject doPostByHttpClient(String url, String data) throws ConnectException {
    
    
        System.out.println("url =" + url);
        System.out.println("data =" + data);
        try {
    
    
        //如果是https 用这种方式
            CloseableHttpClient httpClient = null;
            if (url.toLowerCase().startsWith("https://")) {
    
    
                System.out.println("use ssl");
                httpClient = getHttpsClient();
            } else {
    
    
             //如果是http 用这种方式
                System.out.println("use nonssl");
                httpClient = HttpClients.createDefault();
            }
            HttpPost httpPost = new HttpPost(url);
            //添加响应头
            httpPost.addHeader("Content-Type", "application/json; charset=UTF-8");
            if(data != null){
    
    
                StringEntity se = new StringEntity(data, "UTF-8");
                se.setContentType("text/json");
                se.setContentEncoding(new BasicHeader("Content-Type", "application/json; charset=UTF-8"));
                httpPost.setEntity(se);
            }
            HttpResponse response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
    
    
                throw new ConnectException("连接服务器失败!");
            }
            String s = EntityUtils.toString(response.getEntity());
            JSONObject json = JSONObject.parseObject(s);
            return json;
        } catch (Exception e) {
    
    
            e.printStackTrace();
            System.out.println(" ===== doPostByHttpClient() ERROR ===== ");
            throw new ConnectException(e.getMessage());
        } finally {
    
    
            System.clearProperty("javax.net.debug");
        }
    }

    public static CloseableHttpClient getHttpsClient() throws KeyManagementException, NoSuchAlgorithmException {
    
    
        //采用绕过验证的方式处理https请求
        SSLContext sslcontext = createIgnoreVerifySSL();

        //设置协议http和https对应的处理socket链接工厂的对象
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", new SSLConnectionSocketFactory(sslcontext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER))
                .build();
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);

        //创建自定义的httpclient对象
        CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
        return client;
    }

    public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
    
    
        SSLContext sslContext = SSLContext.getInstance("TLS");
        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;
            }
        };
        sslContext.init(null, new TrustManager[] {
    
     trustManager }, null);
        return sslContext;
    }

    
}

Guess you like

Origin blog.csdn.net/Evain_Wang/article/details/112847762