httpClient工具類


參考的github

使用對象封裝http請求的結果

public class HttpClientResult implements Serializable {

	private static final long serialVersionUID = 2168152194164783950L;

	/**
	 * 響應狀態碼
	 */
	private int code;

	/**
	 * 響應數據
	 */
	private String content;

	public HttpClientResult() {
	}

	public HttpClientResult(int code) {
		this.code = code;
	}

	public HttpClientResult(String content) {
		this.content = content;
	}

	public HttpClientResult(int code, String content) {
		this.code = code;
		this.content = content;
	}

	public int getCode() {
		return code;
	}

	public void setCode(int code) {
		this.code = code;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	@Override
	public String toString() {
		return "HttpClientResult [code=" + code + ", content=" + content + "]";
	}

}

編寫工具類

public class HttpClientUtils {

    // 編碼格式。發送編碼格式統一用UTF-8
    private static final String ENCODING = "UTF-8";

    // 設置連接超時時間,單位毫秒。
    private static final int CONNECT_TIMEOUT = 6000;

    // 請求獲取數據的超時時間(即響應時間),單位毫秒。
    private static final int SOCKET_TIMEOUT = 6000;

    /**
     * 發送get請求;不帶請求頭和請求參數
     *
     * @param url 請求地址
     * @return
     * @throws Exception
     */
    public static HttpClientResult doGet(String url) throws Exception {
        return doGet(url, null, null);
    }

    /**
     * 發送get請求;帶請求參數
     *
     * @param url    請求地址
     * @param params 請求參數集合
     * @return
     * @throws Exception
     */
    public static HttpClientResult doGet(String url, Map<String, String> params) throws Exception {
        return doGet(url, null, params);
    }

    /**
     * 發送get請求;帶請求頭和請求參數
     *
     * @param url     請求地址
     * @param headers 請求頭集合
     * @param params  請求參數集合
     * @return
     * @throws Exception
     */
    public static HttpClientResult doGet(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
        // 創建httpClient對象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 創建訪問的地址
        URIBuilder uriBuilder = new URIBuilder(url);
        if (params != null) {
            Set<Entry<String, String>> entrySet = params.entrySet();
            for (Entry<String, String> entry : entrySet) {
                uriBuilder.setParameter(entry.getKey(), entry.getValue());
            }
        }

        // 創建http對象
        HttpGet httpGet = new HttpGet(uriBuilder.build());
        /**
         * setConnectTimeout:設置連接超時時間,單位毫秒。
         * setConnectionRequestTimeout:設置從connect Manager(連接池)獲取Connection
         * 超時時間,單位毫秒。這個屬性是新加的屬性,因為目前版本是可以共享連接池的。
         * setSocketTimeout:請求獲取數據的超時時間(即響應時間),單位毫秒。 如果訪問一個接口,多少時間內無法返回數據,就直接放棄此次調用。
         */
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
        httpGet.setConfig(requestConfig);

        // 設置請求頭
        packageHeader(headers, httpGet);

        // 創建httpResponse對象
        CloseableHttpResponse httpResponse = null;

        try {
            // 執行請求並獲得響應結果
            return getHttpClientResult(httpResponse, httpClient, httpGet);
        } finally {
            // 釋放資源
            release(httpResponse, httpClient);
        }
    }

    /**
     * 發送post請求;不帶請求頭和請求參數
     *
     * @param url 請求地址
     * @return
     * @throws Exception
     */
    public static HttpClientResult doPost(String url) throws Exception {
        return doPost(url, null, null);
    }

    /**
     * 發送post請求;帶請求參數
     *
     * @param url    請求地址
     * @param params 參數集合
     * @return
     * @throws Exception
     */
    public static HttpClientResult doPost(String url, Map<String, String> params) throws Exception {
        return doPost(url, null, params);
    }

    /**
     * 發送post請求;帶請求頭和請求參數
     *
     * @param url     請求地址
     * @param headers 請求頭集合
     * @param params  請求參數集合
     * @return
     * @throws Exception
     */
    public static HttpClientResult doPost(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
        // 創建httpClient對象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 創建http對象
        HttpPost httpPost = new HttpPost(url);
        /**
         * setConnectTimeout:設置連接超時時間,單位毫秒。
         * setConnectionRequestTimeout:設置從connect Manager(連接池)獲取Connection
         * 超時時間,單位毫秒。這個屬性是新加的屬性,因為目前版本是可以共享連接池的。
         * setSocketTimeout:請求獲取數據的超時時間(即響應時間),單位毫秒。 如果訪問一個接口,多少時間內無法返回數據,就直接放棄此次調用。
         */
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
        httpPost.setConfig(requestConfig);
        // 設置請求頭
		/*httpPost.setHeader("Cookie", "");
		httpPost.setHeader("Connection", "keep-alive");
		httpPost.setHeader("Accept", "application/json");
		httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
		httpPost.setHeader("Accept-Encoding", "gzip, deflate, br");
		httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");*/
        packageHeader(headers, httpPost);

        // 封裝請求參數
        packageParam(params, httpPost);

        // 創建httpResponse對象
        CloseableHttpResponse httpResponse = null;

        try {
            // 執行請求並獲得響應結果
            return getHttpClientResult(httpResponse, httpClient, httpPost);
        } finally {
            // 釋放資源
            release(httpResponse, httpClient);
        }
    }

    /**
     * 發送put請求;不帶請求參數
     *
     * @param url    請求地址
     * @return
     * @throws Exception
     */
    public static HttpClientResult doPut(String url) throws Exception {
        return doPut(url);
    }

    /**
     * 發送put請求;帶請求參數
     *
     * @param url    請求地址
     * @param params 參數集合
     * @return
     * @throws Exception
     */
    public static HttpClientResult doPut(String url, Map<String, String> params) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPut httpPut = new HttpPut(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
        httpPut.setConfig(requestConfig);

        packageParam(params, httpPut);

        CloseableHttpResponse httpResponse = null;

        try {
            return getHttpClientResult(httpResponse, httpClient, httpPut);
        } finally {
            release(httpResponse, httpClient);
        }
    }

    /**
     * 發送delete請求;不帶請求參數
     *
     * @param url    請求地址
     * @return
     * @throws Exception
     */
    public static HttpClientResult doDelete(String url) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpDelete httpDelete = new HttpDelete(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
        httpDelete.setConfig(requestConfig);

        CloseableHttpResponse httpResponse = null;
        try {
            return getHttpClientResult(httpResponse, httpClient, httpDelete);
        } finally {
            release(httpResponse, httpClient);
        }
    }

    /**
     * 發送delete請求;帶請求參數
     *
     * @param url    請求地址
     * @param params 參數集合
     * @return
     * @throws Exception
     */
    public static HttpClientResult doDelete(String url, Map<String, String> params) throws Exception {
        if (params == null) {
            params = new HashMap<String, String>();
        }

        params.put("_method", "delete");
        return doPost(url, params);
    }


    /**
     * 發送上傳文件請求;
     *
     * @param url      請求地址
     * @param params   參數集合
     * @param headers  請求頭集合
     * @param filePath 文件路徑
     * @param fileType 文件類型名
     * @return
     * @throws Exception
     */
    public static HttpClientResult uploadFile(String url,
                                              Map<String, String> params,
                                              Map<String, String> headers,
                                              String filePath,
                                              String fileType) throws Exception {
        final CloseableHttpClient httpClient = HttpClients.createDefault();
        final HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "multipart/form-data");
        packageHeader(headers, httpPost);
        //創建multipart/form-data的entity的builder
        final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        //將文件加在http的post請求中
        final File file = new File(filePath);
        builder.addBinaryBody(
                fileType,
                new FileInputStream(file),
                ContentType.APPLICATION_OCTET_STREAM,
                file.getName()
        );
        if (params != null) {
            final JSONObject jsonObject = new JSONObject();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                jsonObject.put(entry.getKey(), entry.getValue());
            }
            builder.addTextBody(jsonObject.toString(), ContentType.APPLICATION_JSON.toString());
        }
        //生成multipart/form-data的entity
        final HttpEntity multipartEntity = builder.build();
        httpPost.setEntity(multipartEntity);
        CloseableHttpResponse response = null;
        try {
            return getHttpClientResult(response, httpClient, httpPost);
        }finally {
            release(response,httpClient);
        }
    }

    /**
     * Description: 封裝請求頭
     *
     * @param params
     * @param httpMethod
     */
    public static void packageHeader(Map<String, String> params, HttpRequestBase httpMethod) {
        // 封裝請求頭
        if (params != null) {
            Set<Entry<String, String>> entrySet = params.entrySet();
            for (Entry<String, String> entry : entrySet) {
                // 設置到請求頭到HttpRequestBase對象中
                httpMethod.setHeader(entry.getKey(), entry.getValue());
            }
        }
    }

    /**
     * Description: 封裝請求參數
     *
     * @param params
     * @param httpMethod
     * @throws UnsupportedEncodingException
     */
    public static void packageParam(Map<String, String> params, HttpEntityEnclosingRequestBase httpMethod)
            throws UnsupportedEncodingException {
        // 封裝請求參數
        if (params != null) {
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            Set<Entry<String, String>> entrySet = params.entrySet();
            for (Entry<String, String> entry : entrySet) {
                nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }

            // 設置到請求的http對象中
            httpMethod.setEntity(new UrlEncodedFormEntity(nvps, ENCODING));
        }
    }

    /**
     * Description: 獲得響應結果
     *
     * @param httpResponse
     * @param httpClient
     * @param httpMethod
     * @return
     * @throws Exception
     */
    public static HttpClientResult getHttpClientResult(CloseableHttpResponse httpResponse,
                                                       CloseableHttpClient httpClient, HttpRequestBase httpMethod) throws Exception {
        // 執行請求
        httpResponse = httpClient.execute(httpMethod);

        // 獲取返回結果
        if (httpResponse != null && httpResponse.getStatusLine() != null) {
            String content = "";
            if (httpResponse.getEntity() != null) {
                content = EntityUtils.toString(httpResponse.getEntity(), ENCODING);
            }
            return new HttpClientResult(httpResponse.getStatusLine().getStatusCode(), content);
        }
        return new HttpClientResult(HttpStatus.SC_INTERNAL_SERVER_ERROR);
    }

    /**
     * Description: 釋放資源
     *
     * @param httpResponse
     * @param httpClient
     * @throws IOException
     */
    public static void release(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient) throws IOException {
        // 釋放資源
        if (httpResponse != null) {
            httpResponse.close();
        }
        if (httpClient != null) {
            httpClient.close();
        }
    }

}

發送請求至httpbin進行測試

httpbin


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM