HttpClientUtil請求http地址的工具類


直接貼代碼:

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
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;

/**
 * HttpClientUtil
 */
public class HttpClientUtil {

    // 連接主機超時(30s)
    public static final int HTTP_CONNECT_TIMEOUT_30S = 30 * 1000;

    // 從主機讀取數據超時(3min)
    public static final int HTTP_READ_TIMEOUT_3MIN = 180 * 1000;

    /**
     * httpPost
     */
    public static String httpPost(String url, String jsonParam) throws ClientProtocolException, IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);

        // 設置請求頭和請求參數
        if (null != jsonParam && !jsonParam.isEmpty()) {
            StringEntity entity = new StringEntity(jsonParam, "utf-8");
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
        }

        // 超時時間設置
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(HTTP_READ_TIMEOUT_3MIN)
                .setConnectTimeout(HTTP_CONNECT_TIMEOUT_30S).build();
        httpPost.setConfig(requestConfig);

        // 發送請求
        CloseableHttpResponse response = httpclient.execute(httpPost);

        // 獲取返回內容
        try {
            HttpEntity entity = response.getEntity();
            String str = EntityUtils.toString(entity);
            EntityUtils.consume(entity); // 此句關閉了流
            return str;
        } finally {
            response.close();
        }
    }

    /**
     * httpPost get Cookies
     */
    public static Map<String, Object> httpPostGetCookies(String url, String jsonParam) throws ClientProtocolException,
            IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);

        // 設置請求頭和請求參數
        if (null != jsonParam && !jsonParam.isEmpty()) {
            StringEntity entity = new StringEntity(jsonParam, "utf-8");
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
        }

        // 超時時間設置
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(HTTP_READ_TIMEOUT_3MIN)
                .setConnectTimeout(HTTP_CONNECT_TIMEOUT_30S).build();
        httpPost.setConfig(requestConfig);

        // 發送請求
        CloseableHttpResponse response = httpclient.execute(httpPost);

        // 獲取返回內容
        try {
            HttpEntity entity = response.getEntity();
            String str = EntityUtils.toString(entity);
            EntityUtils.consume(entity); // 此句關閉了流

            // 獲取數據內容
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("result", str);

            // 獲取返回到額Cookies
            Header[] headers = response.getHeaders("Set-Cookie");
            map.put("cookies", headers);

            return map;
        } finally {
            response.close();
        }
    }

    /**
     * httpGet
     */
    public static String httpGet(String url) throws ClientProtocolException, IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);

        // 超時時間設置
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(HTTP_READ_TIMEOUT_3MIN)
                .setConnectTimeout(HTTP_CONNECT_TIMEOUT_30S).build();
        httpGet.setConfig(requestConfig);

        // 發送請求
        CloseableHttpResponse response = httpclient.execute(httpGet);

        // 獲取返回內容
        try {
            HttpEntity entity = response.getEntity();
            String strResult = EntityUtils.toString(entity);
            return strResult;
        } finally {
            response.close();
        }
    }

    /**
     * httpGet with Cookies
     */
    public static String httpGetWithCookies(String url, Header[] headers) throws ClientProtocolException, IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);

        // 超時時間設置
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(HTTP_READ_TIMEOUT_3MIN)
                .setConnectTimeout(HTTP_CONNECT_TIMEOUT_30S).build();
        httpGet.setConfig(requestConfig);

        // 設置請求頭
        if (headers != null && headers.length > 0) {
            httpGet.setHeaders(headers);
        }

        // 發送請求
        CloseableHttpResponse response = httpclient.execute(httpGet);

        // 獲取返回內容
        try {
            HttpEntity entity = response.getEntity();
            String strResult = EntityUtils.toString(entity);
            return strResult;
        } finally {
            response.close();
        }
    }

}

 


免責聲明!

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



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