HTTP Client ,post与get工具包

需要的jar包

<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.4</version>
</dependency>
<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpmime</artifactId>
  <version>4.4</version>
</dependency>
<dependency>
  <groupId>net.sf.json-lib</groupId>
  <artifactId>json-lib</artifactId>
  <version>2.4</version>
  <classifier>jdk15</classifier>
</dependency>

 

类一:

package im.qiaofeng.file.fileuploaddownload.utils;

import com.alibaba.fastjson.JSONObject;
import im.qiaofeng.file.fileuploaddownload.constants.ErrorCodeConstants;
import im.qiaofeng.file.fileuploaddownload.exception.UtilException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
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.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

@Slf4j
public class HttpClientUtil {


    public static JSONObject Get(String path, Map<String, Object> queryParams) {
        try {
            HttpClient httpclient = HttpClientMng.getClient();
            Iterator<String> iter = queryParams.keySet().iterator();
            String temp = path + "?";
            while (iter.hasNext()) {
                String key = iter.next();
                temp = temp + key + "=" + queryParams.get(key) + "&";
            }
            String url = temp.substring(0, temp.lastIndexOf("&"));
            HttpGet httpget = new HttpGet(url);
            HttpResponse response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity);
            EntityUtils.consume(entity);
            return JSONObject.parseObject(result);
        } catch (IOException e) {
            log.error("发送get请求失败:" + e);
            throw new UtilException(ErrorCodeConstants.SYSTEM_ERROR);
        }
    }

    public static JSONObject post(String path, String jsonStr) {
        CloseableHttpClient httpClient = null;
        try {
            httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(path);
            //添加传入参数
            httpPost.setEntity(new StringEntity(jsonStr, StandardCharsets.UTF_8));

            //发送相应数据
            CloseableHttpResponse reseponse = httpClient.execute(httpPost);
            HttpEntity res = reseponse.getEntity();
            BufferedReader reader = new BufferedReader(new InputStreamReader(res.getContent(), StandardCharsets.UTF_8));
            String result = "";
            String line;
            while ((line = reader.readLine()) != null) {
                result += line;
            }
            return JSONObject.parseObject(result);
        } catch (Exception e) {
            log.error("发送post请求失败:" + e);
/**
*这里是自定义的错误类,自己用时记得自定义
**/
            throw new UtilException(ErrorCodeConstants.SYSTEM_ERROR);
        }
    }

}

类二:

package im.qiaofeng.file.fileuploaddownload.utils;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.HttpClient;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

@Slf4j
public class HttpClientMng {

    private static HttpClient client = null;

    public static HttpClient getClient() {
        getTrustedHttpClient();
        return client;
    }

    @SuppressWarnings("deprecation")
    private static synchronized void getTrustedHttpClient() {
        try {
            if (client == null) {
                HttpClientBuilder b = HttpClientBuilder.create();
                // 策略:允许加载所有证书
                SSLContext sslContext = null;
                sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                    @Override
                    public boolean isTrusted(java.security.cert.X509Certificate[] arg0, String arg1) {
                        return true;
                    }
                }).build();
                b.setSslcontext(sslContext);
                // 不检测主机名
                HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
                // 创建SSLSocketFactory来加载配置
                SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
                    hostnameVerifier);
                Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                    .<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.getSocketFactory())
                    .register("https", sslSocketFactory).build();
                // 创建connection-manager,配置Registry。支持多线程的使用
                PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(
                    socketFactoryRegistry);
                b.setConnectionManager(connMgr);
                // 构建HttpClient
                client = b.build();
            }
        } catch (Exception e) {
            log.error("获取httpClient对象失败" + e);
        }
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值