SpringBoot系列(二十一)httpClient

一、创建公共处理类

1.1、创建公共处理类HttpUtils

package util;


import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.scheme.SchemeSocketFactory;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


public class HttpUtils {
    public static HttpResponse doGet(String host, String path,  Map<String, Object> headers, Map<String, Object> querys) throws Exception {
        HttpClient httpClient = wrapClient(host);
        HttpGet request = new HttpGet(buildUrl(host, path, querys));
        for (Map.Entry<String, Object> e : headers.entrySet())
            request.addHeader(e.getKey(), e.getValue().toString());

        return httpClient.execute((HttpUriRequest)request);
    }

    public static HttpResponse doPost(String host, String path, Map<String, Object> headers,Map<String, Object> querys, Map<String, Object> bodys) throws Exception {
        HttpClient httpClient = wrapClient(host);
        HttpPost request = new HttpPost(buildUrl(host, path, querys));
        for (Map.Entry<String, Object> e : headers.entrySet())
            request.addHeader(e.getKey(), e.getValue().toString());
        if (bodys != null) {
            StringEntity entity = new StringEntity(JSON.toJSONString(bodys), "utf-8");
            entity.setContentType("application/json; charset=UTF-8");
            //设置请求内容
            request.setEntity(entity);
        }
        //执行请求内容
        HttpResponse response = httpClient.execute(request);
        return response;
    }


    public static HttpResponse doPut(String host, String path,  Map<String, Object> headers, Map<String, Object> querys, Map<String, Object> bodys) throws Exception {
        HttpClient httpClient = wrapClient(host);
        HttpPut request = new HttpPut(buildUrl(host, path, querys));
        for (Map.Entry<String, Object> e : headers.entrySet())
            request.addHeader(e.getKey(), e.getValue().toString());
        if (bodys != null) {
            StringEntity entity = new StringEntity(JSON.toJSONString(bodys), "utf-8");
            entity.setContentType("application/json; charset=UTF-8");
            //设置请求内容
            request.setEntity(entity);
        }
        return httpClient.execute((HttpUriRequest)request);
    }



    public static HttpResponse doDelete(String host, String path,  Map<String, Object> headers, Map<String, Object> querys) throws Exception {
        HttpClient httpClient = wrapClient(host);
        HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
        for (Map.Entry<String, Object> e : headers.entrySet())
            request.addHeader(e.getKey(), e.getValue().toString());
        return httpClient.execute((HttpUriRequest)request);
    }

    private static String buildUrl(String host, String path, Map<String, Object> querys) throws UnsupportedEncodingException {
        StringBuilder sbUrl = new StringBuilder();
        sbUrl.append(host);
        if (!StringUtils.isBlank(path))
            sbUrl.append(path);
        if (null != querys) {
            StringBuilder sbQuery = new StringBuilder();
            for (Map.Entry<String, Object> query : querys.entrySet()) {
                if (0 < sbQuery.length())
                    sbQuery.append("&");
                if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue().toString()))
                    sbQuery.append(query.getValue());
                if (!StringUtils.isBlank(query.getKey())) {
                    sbQuery.append(query.getKey());
                    if (!StringUtils.isBlank(query.getValue().toString())) {
                        sbQuery.append("=");
                        sbQuery.append(URLEncoder.encode(query.getValue().toString(), "utf-8"));
                    }
                }
            }
            if (0 < sbQuery.length())
                sbUrl.append("?").append(sbQuery);
        }
        return sbUrl.toString();
    }

    private static HttpClient wrapClient(String host) {

        HttpClient client = HttpClientBuilder.create().build();

        if (host.startsWith("https://"))
            sslClient((HttpClient)client);
        return (HttpClient)client;
    }
    @Deprecated
    private static void sslClient(HttpClient httpClient) {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            Object object = new Object();
            ctx.init(null, new TrustManager[] { (TrustManager)object }, null);
            SSLSocketFactory ssf = new SSLSocketFactory(ctx);
            ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            ClientConnectionManager ccm = httpClient.getConnectionManager();
            SchemeRegistry registry = ccm.getSchemeRegistry();
            registry.register(new Scheme("https", 443, (SchemeSocketFactory)ssf));
        } catch (KeyManagementException ex) {
            throw new RuntimeException(ex);
        } catch (NoSuchAlgorithmException ex) {
            throw new RuntimeException(ex);
        }
    }
}

1.2创建公共处理类HttpRequestUtils

package util;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;

import java.util.Map;

public class HttpRequestUtils {

    public HttpResponse doGet(String host, String path, Map<String, Object> headers, Map<String, Object> ParamMaps){
        HttpRequest httpRequest = HttpRequest.get(host+path);
        for (Map.Entry<String, Object> e : headers.entrySet())
            httpRequest.header(e.getKey(), e.getValue().toString());
        HttpResponse getResponse = httpRequest.form(ParamMaps).execute();
        return getResponse;
    }

    public HttpResponse doPost(String host, String path, Map<String, Object> headers,Map<String,Object> paramMaps){

        HttpRequest httpRequest = HttpRequest.post(host+path);
        for (Map.Entry<String, Object> e : headers.entrySet())
            httpRequest.header(e.getKey(), e.getValue().toString());
        HttpResponse response = httpRequest.body(JSON.toJSONString(paramMaps)).execute();
        return response;
    }

    public HttpResponse doPut(String host,String path,Map<String,Object> headers,Map<String,Object> paraMaps){
        HttpRequest httpRequest = HttpRequest.put(host+path);
        for (Map.Entry<String, Object> e : headers.entrySet())
            httpRequest.header(e.getKey(), e.getValue().toString());
        HttpResponse response = httpRequest.body(JSON.toJSONString(paraMaps)).execute();
        return response;
    }

    public HttpResponse doDelete(String host,String path,Map<String,Object> headers, Map<String, Object> ParamMaps){

        HttpRequest httpRequest = HttpRequest.delete(host+path);
        for (Map.Entry<String, Object> e : headers.entrySet())
            httpRequest.header(e.getKey(), e.getValue().toString());
        HttpResponse getResponse = httpRequest.form(ParamMaps).execute();
        return getResponse;
    }

}

二、Http传输例子

2.1 Get例子

    /*GET类型*/
    public static void main(String[] args) {
        /*GET类型使用工具类HttpUtils*/
        HttpUtils httpUtils = new HttpUtils();
        String host = "http://192.168.8.10:8083";
        String path = "/api/sample/v1/spu/latest";

        Map<String,Object> headers = new HashMap<>();
        Map<String,Object> querys = new HashMap<>();
        try {
            HttpResponse getResponse = httpUtils.doGet(host,path,headers,querys);

            if (getResponse.getStatusLine().getStatusCode() == 200) {
                String SpunResult = EntityUtils.toString(getResponse.getEntity());
                System.out.println("HttpUtils:"+SpunResult);
                //JSONObject jsonObject = JSON.parseObject(SpunResult);
                //String data = jsonObject.getString("data");
                //JSONObject jsonData = JSON.parseObject(data);
            }
            System.out.println("HttpUtils:"+getResponse);
        } catch (Exception e) {
            e.printStackTrace();
        }

        /*GET类型使用工具类 HttpRequestUtils*/
        HttpRequestUtils httpRequestUtils = new HttpRequestUtils();

        cn.hutool.http.HttpResponse getResponse2 = httpRequestUtils.doGet(host,path,headers, querys);
        if (getResponse2.getStatus() == 200) {
            String body1 = getResponse2.body();
            System.out.println("HttpRequestUtils:"+body1);
        }
        System.out.println("HttpRequestUtils:"+getResponse2);
    }

2.2 Post例子

    /*POST类型*/
    public static void main(String[] args) {

        HttpUtils httpUtils = new HttpUtils();
        String host = "http://192.168.8.10:5000";
        String path = "/v1/banner/createBanner";
        Map<String,Object> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        Map<String,Object> querys = new HashMap<>();
        Map<String,Object> paramMaps = new HashMap<>();

        paramMaps.put("name","banner_fox");
        paramMaps.put("title","banner_title");
        paramMaps.put("version",0);
        /*POST类型使用工具类HttpUtils*/
        try {
            HttpResponse getResponse = httpUtils.doPost(host,path,headers,querys,paramMaps);
            System.out.println("HttpUtils-Post-code:"+getResponse.getStatusLine().getStatusCode());
            if (getResponse.getStatusLine().getStatusCode() == 201) {
                String callbackResult = EntityUtils.toString(getResponse.getEntity());
                System.out.println("HttpUtils-Post:"+callbackResult);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        /*POST类型使用工具类 HttpRequestUtils*/
        HttpRequestUtils httpRequestUtils = new HttpRequestUtils();
        cn.hutool.http.HttpResponse PostResponse2 = httpRequestUtils.doPost(host,path,headers, paramMaps);
        if (PostResponse2.getStatus() == 200) {
            String body1 = PostResponse2.body();
            System.out.println("HttpRequestUtils-Post:"+body1);
        }
        System.out.println("HttpRequestUtils-Post:"+PostResponse2);

    }

2.3 Put例子

    /*PUT类型*/
    public static void main(String[] args) {

        HttpUtils httpUtils = new HttpUtils();
        String host = "http://192.168.8.10:5000";
        String path = String.format("/v1/banner/updateBanner/%s",53);
        Map<String,Object> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        Map<String,Object> querys = new HashMap<>();
        Map<String,Object> paramMaps = new HashMap<>();

        paramMaps.put("id",53);
        paramMaps.put("name","banner_fox_533");
        paramMaps.put("title","banner_title_533");

        /*PUT类型使用工具类HttpUtils*/
        try {
            HttpResponse getResponse = httpUtils.doPut(host,path,headers,querys,paramMaps);
            System.out.println("HttpUtils-Put-code:"+getResponse.getStatusLine().getStatusCode());
            if (getResponse.getStatusLine().getStatusCode() == 201) {
                String callbackResult = EntityUtils.toString(getResponse.getEntity());
                System.out.println("HttpUtils-Put:"+callbackResult);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        /*Put类型使用工具类 HttpRequestUtils*/
        HttpRequestUtils httpRequestUtils = new HttpRequestUtils();
        cn.hutool.http.HttpResponse PutResponse2 = httpRequestUtils.doPut(host,path,headers, paramMaps);
        if (PutResponse2.getStatus() == 201) {
            String body1 = PutResponse2.body();
            System.out.println("HttpRequestUtils-Put:"+body1);
        }
        System.out.println("HttpRequestUtils-Put:"+PutResponse2);
    }

2.4 Delete 例子

   public static void main(String[] args) {

        HttpUtils httpUtils = new HttpUtils();
        String host = "http://192.168.8.10:5000";
        String path = String.format("/v1/banner/deleteBanner/%s",53);
        Map<String,Object> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        Map<String,Object> querys = new HashMap<>();
        Map<String,Object> paramMaps = new HashMap<>();

        /*Delete类型使用工具类HttpUtils*/
        try {
            HttpResponse getResponse = httpUtils.doDelete(host,path,headers,querys);
            System.out.println("HttpUtils-DELETE-code:"+getResponse.getStatusLine().getStatusCode());
            if (getResponse.getStatusLine().getStatusCode() == 201) {
                String callbackResult = EntityUtils.toString(getResponse.getEntity());
                System.out.println("HttpUtils-DELETE:"+callbackResult);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        /*Put类型使用工具类 HttpRequestUtils*/
        HttpRequestUtils httpRequestUtils = new HttpRequestUtils();
        cn.hutool.http.HttpResponse DeleteResponse2 = httpRequestUtils.doDelete(host,path,headers, paramMaps);
        if (DeleteResponse2.getStatus() == 201) {
            String body1 = DeleteResponse2.body();
            System.out.println("HttpRequestUtils-Delete:"+body1);
        }
        System.out.println("HttpRequestUtils-Delete:"+DeleteResponse2);

    }

https://blog.csdn.net/justry_deng/article/details/81042379