HttpClient工具类

package com.utils;
 
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;
 
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
 
/**
 * HttpClient工具类
 */
@Component
public class HttpUtils {
 
    /**
     * 字符编码
     */
    private final static String UTF8 = "utf-8";
    /**
     * 字节流数组大小(1MB)
     */
    private final static int BYTE_ARRAY_LENGTH = 1024 * 1024;
 
    /**
     * 返回忽略https证书的client
     *
     * @return
     * @throws Exception
     */
    public static HttpClient httpsNoCheckClient() throws Exception {
        X509TrustManager trustManager = new X509TrustManager() {
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
 
            @Override
            public void checkClientTrusted(X509Certificate[] xcs, String str) {
            }
 
            @Override
            public void checkServerTrusted(X509Certificate[] xcs, String str) {
            }
        };
        SSLContext ctx = SSLContext.getInstance(SSLConnectionSocketFactory.TLS);
        ctx.init(null, new TrustManager[]{trustManager}, null);
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(ctx,
                NoopHostnameVerifier.INSTANCE);
        return HttpClients.custom().setSSLSocketFactory(sslSocketFactory).build();
    }
 
    /**
     * 执行get请求获取响应
     *
     * @param url 请求地址
     * @return 响应内容
     */
    public static String get(String url) {
        return get(url, null);
    }
 
    /**
     * 执行get请求获取响应
     *
     * @param url     请求地址
     * @param headers 请求头参数
     * @return 响应内容
     */
    public static String get(String url, Map<String, String> headers) {
        return get(url, headers, 5000, 10000);
    }
 
    /**
     * 执行get请求获取响应
     *
     * @param url
     * @param headers
     * @param connectTimeout
     * @param socketTimeout
     * @return
     */
    public static String get(String url, Map<String, String> headers, Integer connectTimeout, Integer socketTimeout) {
        HttpGet get = new HttpGet(url);
        RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(3000).setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout).build();
        get.setConfig(config);
        return getRespString(get, headers);
    }
 
    /**
     * 执行post请求获取响应
     *
     * @param url 请求地址
     * @return 响应内容
     */
    public static String post(String url) {
        return post(url, null);
    }
 
    /**
     * 执行post请求获取响应
     *
     * @param url    请求地址
     * @param params 请求参数
     * @return 响应内容
     */
    public static String post(String url, Map<String, String> params) {
        return post(url, null, params, 5000, 10000);
    }
 
    /**
     * 执行post请求获取响应
     *
     * @param url     请求地址
     * @param headers 请求头参数
     * @param params  请求参数
     * @return 响应内容
     */
    public static String post(String url, Map<String, String> headers, Map<String, String> params, Integer connectTimeout, Integer socketTimeout) {
        HttpPost post = new HttpPost(url);
        post.setEntity(getHttpEntity(params));
        RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(3000).setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout).build();
        post.setConfig(config);
        return getRespString(post, headers);
    }
 
    /**
     * 执行post请求获取响应(请求体为JOSN数据)
     *
     * @param url  请求地址
     * @param json 请求的JSON数据
     * @return 响应内容
     */
    public static String postJson(String url, String json) {
        return postJson(url, null, json);
    }
 
    /**
     * 执行post请求获取响应(请求体为JOSN数据)
     *
     * @param url     请求地址
     * @param headers 请求头参数
     * @param json    请求的JSON数据
     * @return 响应内容
     */
    public static String postJson(String url, Map<String, String> headers, String json) {
        return postJson(url, headers, json, 5000, 10000);
    }
 
    /**
     * 执行post请求获取响应(请求体为JOSN数据)
     *
     * @param url
     * @param headers
     * @param json
     * @param connectTimeout
     * @param socketTimeout
     * @return
     */
    public static String postJson(String url, Map<String, String> headers, String json, Integer connectTimeout, Integer socketTimeout) {
        HttpPost post = new HttpPost(url);
        post.setHeader("Content-type", "application/json");
        post.setEntity(new StringEntity(json, UTF8));
        RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(3000).setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout).build();
        post.setConfig(config);
        return getRespString(post, headers);
    }
 
    /**
     * 执行post请求获取响应(请求体包含文件)
     *
     * @param url    请求地址
     * @param params 请求参数(文件对应的value传File对象)
     * @return 响应内容
     */
    public static String postFile(String url, Map<String, Object> params) {
        return postFile(url, null, params);
    }
 
    /**
     * 执行post请求获取响应(请求体包含文件)
     *
     * @param url     请求地址
     * @param headers 请求头参数
     * @param params  请求参数(文件对应的value传File对象)
     * @return 响应内容
     */
    public static String postFile(String url, Map<String, String> headers, Map<String, Object> params) {
        HttpPost post = new HttpPost(url);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        if (Objects.nonNull(params) && !params.isEmpty()) {
            for (Entry<String, Object> entry : params.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();
                if (Objects.isNull(value)) {
                    builder.addPart(key, new StringBody("", ContentType.TEXT_PLAIN));
                } else {
                    if (value instanceof File) {
                        builder.addPart(key, new FileBody((File) value));
                    } else {
                        builder.addPart(key, new StringBody(value.toString(), ContentType.TEXT_PLAIN));
                    }
                }
            }
        }
        HttpEntity entity = builder.build();
        post.setEntity(entity);
        return getRespString(post, headers);
    }
 
    /**
     * Http Put请求
     *
     * @param url
     * @param json
     * @return
     */
    public static String putJson(String url, String json) {
        return putJson(url, null, json);
    }
 
    /**
     * Http Put 请求,自定义headers
     *
     * @param url
     * @param headers
     * @param json
     * @return
     */
    public static String putJson(String url, Map<String, String> headers, String json) {
        HttpPut put = new HttpPut(url);
        put.setHeader("Content-type", "application/json");
        put.setEntity(new StringEntity(json, UTF8));
        return getRespString(put, headers);
    }
 
    /**
     * 下载文件
     *
     * @param url      下载地址
     * @param path     保存路径(如:D:/images,不传默认当前工程根目录)
     * @param fileName 文件名称(如:hello.jpg)
     */
    public static void download(String url, String path, String fileName) {
        HttpGet get = new HttpGet(url);
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String filePath = null;
        if (Objects.isNull(path) || path.isEmpty()) {
            filePath = fileName;
        } else {
            if (path.endsWith("/")) {
                filePath = path + fileName;
            } else {
                filePath += path + "/" + fileName;
            }
        }
        File file = new File(filePath);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try (FileOutputStream fos = new FileOutputStream(file); InputStream in = getRespInputStream(get, null)) {
            if (Objects.isNull(in)) {
                return;
            }
            byte[] bytes = new byte[BYTE_ARRAY_LENGTH];
            int len = 0;
            while ((len = in.read(bytes)) != -1) {
                fos.write(bytes, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    /**
     * 获取请求体HttpEntity
     *
     * @param params 请求参数
     * @return HttpEntity
     */
    private static HttpEntity getHttpEntity(Map<String, String> params) {
        List<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
        for (Entry<String, String> entry : params.entrySet()) {
            pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        HttpEntity entity = null;
        try {
            entity = new UrlEncodedFormEntity(pairs, UTF8);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return entity;
    }
 
    /**
     * 设置请求头
     *
     * @param request 请求对象
     * @param headers 请求头参数
     */
    private static void setHeaders(HttpUriRequest request, Map<String, String> headers) {
        if (Objects.nonNull(headers) && !headers.isEmpty()) {
            // 请求头不为空,则设置对应请求头
            for (Entry<String, String> entry : headers.entrySet()) {
                request.setHeader(entry.getKey(), entry.getValue());
            }
        } else {
            // 请求为空时,设置默认请求头
            request.setHeader("Connection", "keep-alive");
            request.setHeader("Accept-Encoding", "gzip, deflate, br");
            request.setHeader("Accept", "*/*");
            request.setHeader("User-Agent",
                    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36");
        }
    }
 
    /**
     * 执行请求,获取响应流
     *
     * @param request 请求对象
     * @return 响应内容
     */
    private static InputStream getRespInputStream(HttpUriRequest request, Map<String, String> headers) {
        // 设置请求头
        setHeaders(request, headers);
        // 获取响应对象
        HttpResponse response = null;
        try {
            HttpClient httpClient = httpsNoCheckClient();
            response = httpClient.execute(request);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        // 获取Entity对象
        HttpEntity entity = response.getEntity();
        // 获取响应信息流
        InputStream in = null;
        if (Objects.nonNull(entity)) {
            try {
                in = entity.getContent();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return in;
    }
 
    /**
     * 执行请求,获取响应内容
     *
     * @param request 请求对象
     * @return 响应内容
     */
    private static String getRespString(HttpUriRequest request, Map<String, String> headers) {
        byte[] bytes = new byte[BYTE_ARRAY_LENGTH];
        int len = 0;
        try (InputStream in = getRespInputStream(request, headers);
             ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            if (Objects.isNull(in)) {
                return "";
            }
            while ((len = in.read(bytes)) != -1) {
                bos.write(bytes, 0, len);
            }
            return bos.toString(UTF8);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
 
    /**
     *
     * @param username
     * @param password
     * @param uri
     * @param json
     * @return
     */
 
    public static int httpClientWithBasicAuth(String username, String password, String uri, JSONObject json) {
        try {
            // 创建HttpClientBuilder
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
            CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
            HttpPost httpPost = new HttpPost(uri);
            //添加http头信息
            httpPost.addHeader("Authorization", "Basic " + Base64.getUrlEncoder().encodeToString((username + ":" + password).getBytes()));
 
//            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
//
//            paramMap.forEach((k,v)->{
//                builder.addPart(k, new StringBody(v, ContentType.APPLICATION_JSON));
//            });
//            HttpEntity postEntity = builder.build();
            StringEntity s = new StringEntity(json.toString(), StandardCharsets.UTF_8);
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");//发送json数据需要设置contentType
            httpPost.setEntity(s);
//            httpPost.setEntity(postEntity);
            String result = "";
            HttpResponse httpResponse = null;
            HttpEntity entity = null;
            try {
                httpResponse = closeableHttpClient.execute(httpPost);
                entity = httpResponse.getEntity();
                if( entity != null ){
                    result = EntityUtils.toString(entity);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
 
            // 关闭连接
            closeableHttpClient.close();
            System.out.println(result);
        }catch (Exception e) {
            System.out.println(e.getStackTrace());
        }
        return 0;
    }
 
    /**
     * 
     * @param username
     * @param password
     * @param url
     * @param json
     * @return
     */
    public static String sendPost(String username, String password,String url, JSONObject json) {
        DefaultHttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        post.addHeader("Authorization", "Basic " + Base64.getUrlEncoder().encodeToString((username + ":" + password).getBytes()));
        JSONObject jsonObject = null;
        try {
            StringEntity s = new StringEntity(json.toString(), StandardCharsets.UTF_8);
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");//发送json数据需要设置contentType
            post.setEntity(s);
            HttpResponse res = client.execute(post);
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = res.getEntity();
                String result = EntityUtils.toString(res.getEntity());// 返回json格式:
                return result;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return "";
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jin-进

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值