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;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章