httpUtil

需要在maven中导入的依赖:

        <!--http通讯依赖-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.8</version>
        </dependency>

 

自己组建的httpReqModel以及httpResqModel(后续功能强大了,我这边会继续添加的)

public class HttpReqModel {
    private String url;
    private Map<String,String> header;
    private Map<String,String> params;
    private int readTimeout;

    public int getReadTimeout() {
        return readTimeout;
    }

    public void setReadTimeout(int readTimeout) {
        this.readTimeout = readTimeout;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public Map<String, String> getHeader() {
        return header;
    }

    public void setHeader(Map<String, String> header) {
        this.header = header;
    }

    public Map<String, String> getParams() {
        return params;
    }

    public void setParams(Map<String, String> params) {
        this.params = params;
    }
}
public class HttpResqModel {
    private int statusCode;
    private String returnMsg;

    public int getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }

    public String getReturnMsg() {
        return returnMsg;
    }

    public void setReturnMsg(String returnMsg) {
        this.returnMsg = returnMsg;
    }
}

然后就是httpUtil了

import com.eszb.john.sbsm.common.exception.HttpStatusException;
import com.eszb.john.sbsm.common.exception.ParseMsgException;
import com.eszb.john.sbsm.common.exception.TelnetException;
import com.eszb.john.sbsm.common.net.model.HttpReqModel;
import com.eszb.john.sbsm.common.net.model.HttpResqModel;
import org.apache.http.*;
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.utils.URIBuilder;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.util.LinkedList;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

public class HttpUtil {
    /**
     * 连接池中的最大连接数
     */
    private static final int MAX_CONN_TOTAL = 10;
    /**
     * 连接同一个route最大的并发数
     */
    private static int MAX_CONN_PER_ROUTE = 10;
    /**
     * 从连接池中获取可用连接最大超时时间 单位:毫秒
     */
    private static int CONNECT_REQUEST_TIMEOUT = 1000;
    /**
     * 连接目标url最大超时 单位:毫秒
     */
    private static int CONNECT_TIMEOUT = 1000;
    /**
     * 等待响应(读数据)最大超时 单位:毫秒
     */
    private static int SOCKET_TIMEOUT = 1000;

    /**
     * httpGet方法
     *
     * @param reqModel
     * @return
     * @throws TelnetException
     * @throws URISyntaxException
     * @throws IOException
     * @throws HttpStatusException
     */
    public static HttpResqModel httpGet(HttpReqModel reqModel) throws TelnetException, URISyntaxException, IOException, HttpStatusException, ParseMsgException {
        String url = reqModel.getUrl();
        if (Objects.isNull(url)) {
            throw new TelnetException("request httpGet Method url为空");
        }
        URIBuilder uriBuilder = new URIBuilder(url);
        //设置请求参数
        Map<String, String> params = reqModel.getParams();
        if (!CollectionUtils.isEmpty(params)) {
            LinkedList<NameValuePair> list = new LinkedList<>();
            Set<String> keySet = params.keySet();
            for (String k : keySet) {
                list.add(new BasicNameValuePair(k, params.get(k)));
            }
            uriBuilder.setParameters(list);
        }

        HttpGet httpGet = new HttpGet(uriBuilder.build());
        //设置请求头
        Map<String, String> header = reqModel.getHeader();
        if (!CollectionUtils.isEmpty(header)) {
            Set<String> keySet = header.keySet();
            for (String k : keySet) {
                httpGet.addHeader(k, header.get(k));
            }
        }
        //设置读取时间
        int socketTimeout = SOCKET_TIMEOUT;
        if (0 != reqModel.getReadTimeout()) {
            socketTimeout = reqModel.getReadTimeout();
        }
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(CONNECT_REQUEST_TIMEOUT)
                .setConnectTimeout(CONNECT_TIMEOUT)
                .setSocketTimeout(socketTimeout)
                .build();

        HttpClient httpClient = HttpClientBuilder.create().setMaxConnTotal(MAX_CONN_TOTAL)
                .setMaxConnPerRoute(MAX_CONN_PER_ROUTE)
                .setDefaultRequestConfig(requestConfig)
                .build();

        HttpResponse httpResponse = null;
        try {
            //执行http请求
            httpResponse = httpClient.execute(httpGet);
        } catch (IOException e) {
            throw new IOException();
        }
        StatusLine statusLine = httpResponse.getStatusLine();
        HttpResqModel resqModel = new HttpResqModel();
        int statusCode = statusLine.getStatusCode();
        resqModel.setStatusCode(statusCode);

        //非200状态的处理
        if (HttpStatus.SC_OK != statusCode) {
            throw new HttpStatusException(statusCode, null);
        }
        HttpEntity httpEntity = httpResponse.getEntity();
        String entity = null;
        try {
            entity = EntityUtils.toString(httpEntity, "utf-8");
        } catch (IOException e) {
            throw new ParseMsgException(statusCode,"报文数据报文解析异常"+httpEntity.toString());
        }
        resqModel.setReturnMsg(entity);
        return resqModel;
    }

    /**
     * httpPost方法
     *
     * @param reqModel
     * @return
     */
    public static HttpResqModel httpPost(HttpReqModel reqModel) throws TelnetException, HttpStatusException, ParseMsgException, UnsupportedEncodingException {
        String url = reqModel.getUrl();
        if (Objects.isNull(url)) {
            throw new TelnetException("request httpGet Method url为空");
        }
        HttpPost httpPost = new HttpPost(url);
        //设置post请求头
        Map<String, String> header = reqModel.getHeader();
        if (!CollectionUtils.isEmpty(header)) {
            Set<String> keySet = header.keySet();
            for (String k : keySet) {
                httpPost.addHeader(k, header.get(k));
            }
        }
        //设置参数
        Map<String, String> params = reqModel.getParams();
        if (!CollectionUtils.isEmpty(header)) {
            LinkedList<NameValuePair> pairs = new LinkedList<>();
            Set<String> keySet = params.keySet();
            for (String k : keySet) {
                pairs.add(new BasicNameValuePair(k,params.get(k)));
            }
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs,"utf-8");
            httpPost.setEntity(entity);
        }
        //设置读取时间
        int socketTimeout = SOCKET_TIMEOUT;
        if (0 != reqModel.getReadTimeout()) {
            socketTimeout = reqModel.getReadTimeout();
        }
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(CONNECT_REQUEST_TIMEOUT)
                .setConnectTimeout(CONNECT_TIMEOUT)
                .setSocketTimeout(socketTimeout)
                .build();

        HttpClient httpClient = HttpClientBuilder.create().setMaxConnTotal(MAX_CONN_TOTAL)
                .setMaxConnPerRoute(MAX_CONN_PER_ROUTE)
                .setDefaultRequestConfig(requestConfig)
                .build();

        HttpResponse response = null;
            //执行http请求
        try {
            response = httpClient.execute(httpPost);
        } catch (IOException e) {
            e.printStackTrace();
        }

        StatusLine statusLine = response.getStatusLine();
        HttpResqModel resqModel = new HttpResqModel();
        int statusCode = statusLine.getStatusCode();
        resqModel.setStatusCode(statusCode);

        //非200状态的处理
        if (HttpStatus.SC_OK != statusCode) {
            throw new HttpStatusException(statusCode, null);
        }
        HttpEntity httpEntity = response.getEntity();
        String entity = null;
        try {
            entity = EntityUtils.toString(httpEntity, "utf-8");
        } catch (IOException e) {
            throw new ParseMsgException(statusCode,"报文数据报文解析异常"+httpEntity.toString());
        }
        resqModel.setReturnMsg(entity);
        return resqModel;
    }
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值