http請求封裝JSONObject(基於httpclient4.5.10)

http請求封裝JSONObject參數(基於httpclient4.5.10)

導入Apache POI Maven jar包

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<!-- SpringBoot 整合 HTTPclient -->
<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>4.5.10</version>
</dependency>

<!-- SpringBoot 整合 alibabaJSON -->
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>fastjson</artifactId>
	<version>1.2.47</version>
</dependency>

<!-- commons-io -->
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
	<groupId>commons-io</groupId>
	<artifactId>commons-io</artifactId>
	<version>2.4</version>
</dependency>

編寫工具類

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 *  http請求封裝JSONObject(基於httpclient4.5.10)
 *
 *  @author YeZhiJian
 *
 */
public class HttpClientUtil {

    /**
     *  Get請求
     * @param url
     * @param jsonObject
     * @return
     */
    public static String doGet(String url, JSONObject jsonObject){
        url = getUrl(url, jsonObject);
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String result = "";
        // 通過址默認配置創建一個httpClient實例
        httpClient = HttpClients.createDefault();
        // 創建httpGet遠程連接實例
        HttpGet httpGet = new HttpGet(url);
        // 設置頭部信息以及鑑權
        httpGet.setHeader("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
        // 設置請求參數
        RequestConfig requestConfig = RequestConfig.custom().
                setConnectTimeout(35000)// 連接主機服務超時時間
                .setConnectionRequestTimeout(35000)// 請求超時時間
                .setSocketTimeout(60000)// 數據讀取超時時間
                .build();
        // 爲httpGet實例設置配置
        httpGet.setConfig(requestConfig);
        // 執行get請求得到返回對象
        try {
            response = httpClient.execute(httpGet);
            // 通過返回對象獲取返回數據
            HttpEntity entity = response.getEntity();
            // 通過EntityUtils中的toString方法將結果轉換爲字符串
            result = EntityUtils.toString(entity);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 關閉資源
            if (null != response) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 關閉連接
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    /**
     *  組裝Get請求路徑
     * @param url
     * @return
     */
    private static String getUrl(String url, JSONObject jsonObject){
        String result = "";
        // 獲取所有key
        Iterator<String> keys = jsonObject.keySet().iterator();
        while (keys.hasNext()) {
            // 填充地址
            String key = keys.next();
            result = result + "&" + key + "=" + jsonObject.get(key);
        }
        if (!"".equals(result)){
            result = result.replaceFirst("&", "?");
        }
        url += result;
        return url;
    }

    /**
     *  組裝Post請求路徑
     * @param url
     * @param jsonObject
     * @return
     */
    public static String doPost(String url, JSONObject jsonObject) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        String result = "";
        // 創建httpClient實例
        httpClient = HttpClients.createDefault();
        // 創建httpPost遠程連接實例
        HttpPost httpPost = new HttpPost(url);
        // 配置請求參數實例
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(35000)// 設置連接主機服務超時時間
                .setConnectionRequestTimeout(35000)// 設置連接請求超時時間
                .setSocketTimeout(60000)// 設置讀取數據連接超時時間
                .build();
        // 爲httpPost實例設置配置
        httpPost.setConfig(requestConfig);
        // 設置請求頭
        httpPost.addHeader("Content-Type", "application/json");
        // 封裝post請求參數
        if (jsonObject.size() > 0){
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            Iterator<Map.Entry<String, Object>> iterator = jsonObject.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Object> mapEntry = iterator.next();
                nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString()));
            }
            // 爲httpPost設置封裝好的請求參數
            try {
                httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            try {
                // httpClient對象執行post請求,並返回響應參數對象
                httpResponse = httpClient.execute(httpPost);
                // 從響應對象中獲取響應內容
                HttpEntity entity = httpResponse.getEntity();
                result = EntityUtils.toString(entity);
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                // 關閉資源
                if (null != httpResponse) {
                    try {
                        httpResponse.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (null != httpClient) {
                    try {
                        httpClient.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return result;
    }

}
發佈了7 篇原創文章 · 獲贊 0 · 訪問量 824
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章