HTTP 接口调用utils包

 下面是utils包

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
public class HttpUtil {

    /**
     * 创建get请求
     */
    public static String get(String url, Map<String, Object> query, Map<String, String> header, Integer timeout)
            throws Exception {
        String result = null;
        // ssl验证
        SSLConnectionSocketFactory sslsf;
        try {
            sslsf = new SSLConnectionSocketFactory(
                    SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(),
                    NoopHostnameVerifier.INSTANCE);
        } catch (Exception e) {
            log.error("", e);
            throw new Exception(e.getMessage());
        }
        try (CloseableHttpClient httpClient = HttpClientBuilder.create().setSSLSocketFactory(sslsf).build()) {
            RequestConfig requestConfig = RequestConfig.custom()
                    // 设置连接超时时间(单位毫秒)
                    .setConnectTimeout(timeout)
                    // 设置请求超时时间(单位毫秒)
                    .setConnectionRequestTimeout(timeout)
                    // socket读写超时时间(单位毫秒)
                    .setSocketTimeout(timeout)
                    // 设置是否允许重定向(默认为true)
                    .setRedirectsEnabled(false).build();
            if (query != null) {
                for (String name : query.keySet()) {
                    if (url.contains("?")) {
                        url = url + "&" + name + "=" + (query.get(name) == null ? "" : query.get(name).toString());
                    } else {
                        url = url + "?" + name + "=" + (query.get(name) == null ? "" : query.get(name).toString());
                    }
                }
            }
            HttpGet httpGet = new HttpGet(url);
            httpGet.setConfig(requestConfig);
            if (header != null) {
                header.forEach(httpGet::setHeader);
            }
            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                HttpEntity responseEntity = response.getEntity();
                if (responseEntity != null) {
                    result = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
                }
//                if (response.getStatusLine().getStatusCode() == 200) {
//                    if (responseEntity != null) {
//                        result = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
//                    }
//                }
            }
            httpClient.close();
        } catch (IOException e) {
            log.error("", e);
            throw new Exception("请求提供者接口异常!");
        }
        return result;
    }

    /**
     * post
     * 发起json请求
     */
    public static String postJson(String url, Map<String, Object> body, Map<String, String> header, Integer timeout)
            throws Exception {
        String result = null;
        // ssl验证
        SSLConnectionSocketFactory sslsf;
        try {
            sslsf = new SSLConnectionSocketFactory(
                    SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(),
                    NoopHostnameVerifier.INSTANCE);
        } catch (Exception e) {
            log.error("", e);
            throw new Exception(e.getMessage());
        }
        try (CloseableHttpClient httpClient = HttpClientBuilder.create().setSSLSocketFactory(sslsf).build()) {
            RequestConfig requestConfig = RequestConfig.custom()
                    // 设置连接超时时间(单位毫秒)
                    .setConnectTimeout(timeout)
                    // 设置请求超时时间(单位毫秒)
                    .setConnectionRequestTimeout(timeout)
                    // socket读写超时时间(单位毫秒)
                    .setSocketTimeout(timeout)
                    // 设置是否允许重定向(默认为true)
                    .setRedirectsEnabled(false).build();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setConfig(requestConfig);
            StringEntity entity = new StringEntity(JSONObject.toJSONString(body), StandardCharsets.UTF_8);
            httpPost.setEntity(entity);
            httpPost.setHeader("Content-Type", "application/json;charset=utf-8");

            if (header != null) {
                header.forEach(httpPost::setHeader);
            }
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                HttpEntity responseEntity = response.getEntity();
                if (responseEntity != null) {
                    result = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
                }
//                if (response.getStatusLine().getStatusCode() == 200) {
//                    if (responseEntity != null) {
//                        result = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
//                    }
//                }
            }
            httpClient.close();
        } catch (IOException e) {
            log.error("", e);
            throw new Exception("请求提供者接口异常!");
        }
        return result;
    }

    /**
     * post
     * 发起urlencoded请求
     */
    public static String postUrlencoded(String url, Map<String, Object> body, Map<String, String> header, Integer timeout)
            throws Exception {
        String result = null;
        // ssl验证
        SSLConnectionSocketFactory sslsf;
        try {
            sslsf = new SSLConnectionSocketFactory(
                    SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(),
                    NoopHostnameVerifier.INSTANCE);
        } catch (Exception e) {
            log.error("", e);
            throw new Exception(e.getMessage());
        }
        try (CloseableHttpClient httpClient = HttpClientBuilder.create().setSSLSocketFactory(sslsf).build()) {
            RequestConfig requestConfig = RequestConfig.custom()
                    // 设置连接超时时间(单位毫秒)
                    .setConnectTimeout(timeout)
                    // 设置请求超时时间(单位毫秒)
                    .setConnectionRequestTimeout(timeout)
                    // socket读写超时时间(单位毫秒)
                    .setSocketTimeout(timeout)
                    // 设置是否允许重定向(默认为true)
                    .setRedirectsEnabled(false).build();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setConfig(requestConfig);

            List<NameValuePair> form = new ArrayList<NameValuePair>();
            if (body != null) {
                for (String name : body.keySet()) {
                    form.add(new BasicNameValuePair(name, body.get(name) == null ? "" : body.get(name).toString()));
                }
            }
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(form, StandardCharsets.UTF_8);
            httpPost.setEntity(entity);
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

            if (header != null) {
                header.forEach(httpPost::setHeader);
            }
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                HttpEntity responseEntity = response.getEntity();
                if (responseEntity != null) {
                    result = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
                }
//                if (response.getStatusLine().getStatusCode() == 200) {
//                    if (responseEntity != null) {
//                        result = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
//                    }
//                }
            }
            httpClient.close();
        } catch (IOException e) {
            log.error("", e);
            throw new Exception("请求提供者接口异常!");
        }
        return result;
    }

    /**
     * post
     * 发起multipart请求
     */
    public static String postMultipart(String url, Map<String, Object> body, Map<String, String> header, Integer timeout)
            throws Exception {
        String result = null;
        // ssl验证
        SSLConnectionSocketFactory sslsf;
        try {
            sslsf = new SSLConnectionSocketFactory(
                    SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(),
                    NoopHostnameVerifier.INSTANCE);
        } catch (Exception e) {
            log.error("", e);
            throw new Exception(e.getMessage());
        }
        try (CloseableHttpClient httpClient = HttpClientBuilder.create().setSSLSocketFactory(sslsf).build()) {
            RequestConfig requestConfig = RequestConfig.custom()
                    // 设置连接超时时间(单位毫秒)
                    .setConnectTimeout(timeout)
                    // 设置请求超时时间(单位毫秒)
                    .setConnectionRequestTimeout(timeout)
                    // socket读写超时时间(单位毫秒)
                    .setSocketTimeout(timeout)
                    // 设置是否允许重定向(默认为true)
                    .setRedirectsEnabled(false).build();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setConfig(requestConfig);

            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            builder.setCharset(StandardCharsets.UTF_8);
            builder.setContentType(ContentType.MULTIPART_FORM_DATA);
            if (body != null) {
                for (String name : body.keySet()) {
                    builder.addPart(name,
                            new StringBody(body.get(name) == null ? "" : body.get(name).toString(),
                                    ContentType.create("text/plain", Consts.UTF_8)));
                }
            }
            httpPost.setEntity(builder.build());

            if (header != null) {
                header.forEach(httpPost::setHeader);
            }
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                HttpEntity responseEntity = response.getEntity();
                if (responseEntity != null) {
                    result = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
                }
//                if (response.getStatusLine().getStatusCode() == 200) {
//                    if (responseEntity != null) {
//                        result = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
//                    }
//                }
            }
            httpClient.close();
        } catch (IOException e) {
            log.error("", e);
            throw new Exception("请求提供者接口异常!");
        }
        return result;
    }

    /**
     * post+xml
     * 发起soap请求
     */
    public static String soap(String url, Map<String, Object> body, Map<String, String> header, Integer timeout)
            throws Exception {
        String result = null;
        // ssl验证
        SSLConnectionSocketFactory sslsf;
        try {
            sslsf = new SSLConnectionSocketFactory(
                    SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(),
                    NoopHostnameVerifier.INSTANCE);
        } catch (Exception e) {
            log.error("", e);
            throw new Exception(e.getMessage());
        }
        try (CloseableHttpClient httpClient = HttpClientBuilder.create().setSSLSocketFactory(sslsf).build()) {
            RequestConfig requestConfig = RequestConfig.custom()
                    // 设置连接超时时间(单位毫秒)
                    .setConnectTimeout(timeout)
                    // 设置请求超时时间(单位毫秒)
                    .setConnectionRequestTimeout(timeout)
                    // socket读写超时时间(单位毫秒)
                    .setSocketTimeout(timeout)
                    // 设置是否允许重定向(默认为true)
                    .setRedirectsEnabled(false).build();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setConfig(requestConfig);

            StringBuffer sb = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            sb.append("<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n" +
                    "  xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" \n" +
                    "  xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">");
            sb.append("<soap:Body>");
            if (body != null) {

                String method = body.get("method") == null ? "" : body.get("method").toString();
                String namespace = body.get("namespace") == null ? "" : body.get("namespace").toString();
                sb.append("<ns1:" + method + " soap:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" \n" +
                        "  xmlns:ns1=" + "\"" + namespace + "\">");

                body.remove("method");
                body.remove("namespace");

                for (String name : body.keySet()) {
                    sb.append("<" + name + " xsi:type=\"xsd:string\">" +
                            (body.get(name) == null ? "" : body.get(name).toString()) + "</" + name + ">");
                }

                sb.append("</ns1:" + method + ">");
            }
            sb.append("</soap:Body>");
            sb.append("</soap:Envelope>");
            httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
            httpPost.setHeader("SOAPAction", "\"\"");
            StringEntity entity = new StringEntity(sb.toString(), StandardCharsets.UTF_8);
            httpPost.setEntity(entity);
            if (header != null) {
                header.forEach(httpPost::setHeader);
            }
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                HttpEntity responseEntity = response.getEntity();
                if (responseEntity != null) {
                    result = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
                }
//                if (response.getStatusLine().getStatusCode() == 200) {
//                    if (responseEntity != null) {
//                        result = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
//                    }
//                }
            }
            httpClient.close();
        } catch (IOException e) {
            log.error("", e);
            throw new Exception("请求提供者接口异常!");
        }
        return result;
    }

}

需要的依赖 其他用到啥依赖到时候我在补充 但是这个是必须要的

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5</version>
        </dependency>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值