使用HttpClient訪問接口(Rest接口和普通接口)


這里總結一下使用HttpClient訪問外部接口的用法。后期如果發現有什么缺陷會更改。歡迎讀者指出此方法的不足之處。

首先,創建一個返回實體:

public class HttpResult {
    // 響應的狀態碼
    private int code;

    // 響應的響應體
    private String body;

    public HttpResult(int code, String body) {
        this.code = code;
        this.body = body;
    }
	//省略get/set
}

創建一個HttpClientUtil:

public class HttpClientUtil {

    private static CloseableHttpClient httpClient =  HttpClients.createDefault();	//用static實現單例,此處不完善,當多線程時會出現問題。

    /**
     * 帶參數的get請求
     * 
     * @param url
     * @param map
     * @return
     * @throws Exception
     */
    public static HttpResult doGet(String url, Map<String, Object> map) throws Exception {

        // 聲明URIBuilder
        URIBuilder uriBuilder = new URIBuilder(url);

        // 判斷參數map是否為非空
        if (map != null) {
            // 遍歷參數
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                // 設置參數
                uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
            }
        }

        // 2 創建httpGet對象,相當於設置url請求地址
        HttpGet httpGet = new HttpGet(uriBuilder.build());

        // 3 使用HttpClient執行httpGet,相當於按回車,發起請求
        CloseableHttpResponse response = httpClient.execute(httpGet);

        // 4 解析結果,封裝返回對象httpResult,相當於顯示相應的結果
        // 狀態碼
        // response.getStatusLine().getStatusCode();
        // 響應體,字符串,如果response.getEntity()為空,下面這個代碼會報錯,所以解析之前要做非空的判斷
        // EntityUtils.toString(response.getEntity(), "UTF-8");
        HttpResult httpResult = null;
        // 解析數據封裝HttpResult
        if (response.getEntity() != null) {
            httpResult = new HttpResult(response.getStatusLine().getStatusCode(),
                    EntityUtils.toString(response.getEntity(), "UTF-8"));
        } else {
            httpResult = new HttpResult(response.getStatusLine().getStatusCode(), "");
        }

        // 返回
        return httpResult;
    }

    /**
     * 不帶參數的get請求
     * 
     * @param url
     * @return
     * @throws Exception
     */
    public static HttpResult doGet(String url) throws Exception {
        HttpResult httpResult = doGet(url, null);
        return httpResult;
    }

    /**
     * 帶參數的post請求
     * 
     * @param url
     * @return
     * @throws Exception
     */
    public static HttpResult doPost(String url, Map<String, Object> reqMap, Map<String,String> headersMap) throws Exception {
        // 聲明httpPost請求
        HttpPost httpPost = new HttpPost(url);
        for (Map.Entry<String, String> entry: headersMap.entrySet())
            httpPost.addHeader(entry.getKey(), entry.getValue());

        // 判斷map不為空
        if (reqMap != null) {

            // 創建form表單對象
            StringEntity formEntity = new StringEntity(JSON.toJSONString(reqMap), "UTF-8");

            // 把表單對象設置到httpPost中
            httpPost.setEntity(formEntity);
        }

        // 使用HttpClient發起請求,返回response
        CloseableHttpResponse response = httpClient.execute(httpPost);

        // 解析response封裝返回對象httpResult
        HttpResult httpResult = null;
        if (response.getEntity() != null) {
            httpResult = new HttpResult(response.getStatusLine().getStatusCode(),
                    EntityUtils.toString(response.getEntity(), "UTF-8"));
        } else {
            httpResult = new HttpResult(response.getStatusLine().getStatusCode(), "");
        }

        // 返回結果
        return httpResult;
    }

    /**
     * 不帶參數的post請求
     * 
     * @param url
     * @return
     * @throws Exception
     */
    public static HttpResult doPost(String url) throws Exception {
        HttpResult httpResult = doPost(url, null,null);
        return httpResult;
    }

    /**
     * 帶參數的Put請求
     * 
     * @param url
     * @param map
     * @return
     * @throws Exception
     */
    public static HttpResult doPut(String url, Map<String, Object> map) throws Exception {
        // 聲明httpPost請求
        HttpPut httpPut = new HttpPut(url);

        // 判斷map不為空
        if (map != null) {
            // 聲明存放參數的List集合
            List<NameValuePair> params = new ArrayList<NameValuePair>();

            // 遍歷map,設置參數到list中
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }

            // 創建form表單對象
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "UTF-8");

            // 把表單對象設置到httpPost中
            httpPut.setEntity(formEntity);
        }

        // 使用HttpClient發起請求,返回response
        CloseableHttpResponse response = httpClient.execute(httpPut);

        // 解析response封裝返回對象httpResult
        HttpResult httpResult = null;
        if (response.getEntity() != null) {
            httpResult = new HttpResult(response.getStatusLine().getStatusCode(),
                    EntityUtils.toString(response.getEntity(), "UTF-8"));
        } else {
            httpResult = new HttpResult(response.getStatusLine().getStatusCode(), "");
        }

        // 返回結果
        return httpResult;
    }

    /**
     * 帶參數的Delete請求
     * 
     * @param url
     * @param map
     * @return
     * @throws Exception
     */
    public static HttpResult doDelete(String url, Map<String, Object> map) throws Exception {

        // 聲明URIBuilder
        URIBuilder uriBuilder = new URIBuilder(url);

        // 判斷參數map是否為非空
        if (map != null) {
            // 遍歷參數
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                // 設置參數
                uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
            }
        }

        // 2 創建httpGet對象,相當於設置url請求地址
        HttpDelete httpDelete = new HttpDelete(uriBuilder.build());

        // 3 使用HttpClient執行httpGet,相當於按回車,發起請求
        CloseableHttpResponse response = httpClient.execute(httpDelete);

        // 4 解析結果,封裝返回對象httpResult,相當於顯示相應的結果
        // 狀態碼
        // response.getStatusLine().getStatusCode();
        // 響應體,字符串,如果response.getEntity()為空,下面這個代碼會報錯,所以解析之前要做非空的判斷
        // EntityUtils.toString(response.getEntity(), "UTF-8");
        HttpResult httpResult = null;
        // 解析數據封裝HttpResult
        if (response.getEntity() != null) {
            httpResult = new HttpResult(response.getStatusLine().getStatusCode(),
                    EntityUtils.toString(response.getEntity(), "UTF-8"));
        } else {
            httpResult = new HttpResult(response.getStatusLine().getStatusCode(), "");
        }

        // 返回
        return httpResult;
    }

    /**
     * 返回常用請求頭
     * @return
     */
    public static Map<String, String> commentHeader(){
        Map<String, String> map = new HashMap<>();
        map.put("Content-Type", "application/json");
        return map;
    }
}

測試一下:

package cn.xxxxxx.httpclient.test;

import java.util.HashMap;
import java.util.Map;

import org.junit.Before;
import org.junit.Test;

import cn.itcast.httpclient.APIService;
import cn.itcast.httpclient.HttpResult;

public class APIServiceTest {

    // 查詢
    @Test
    public void testGet() throws Exception {
        // http://manager.aaaaaa.com/rest/item/interface/{id}

        String url = "http://manager.aaaaaa.com/rest/item/interface/42";

        HttpResult httpResult = HttpClientUtil.doGet(url);

        System.out.println(httpResult.getCode());
        System.out.println(httpResult.getBody());

    }

	// 查詢
    @Test
    public void testPost() throws Exception {
      	//設置參數
        Map reqMap = new HashMap();
		reqMap.put("distCode", arsArg.getDistCode());
		HttpResult httpResult = null;
		try {
          	//RestUrlsCommons.RMDS_DISTRICT_FINDBYDISTCODE為url
          	//reqMap:請求參數
          	//HttpClientUtil.commentHeader():請求頭
			httpResult = HttpClientUtil.doPost(RestUrlsCommons.RMDS_DISTRICT_FINDBYDISTCODE, reqMap, HttpClientUtil.commentHeader());
		} catch (Exception e) {
			e.printStackTrace();
		}

        System.out.println(httpResult.getCode());
        System.out.println(httpResult.getBody());
    }

}

參考資料:使用HttpClient調用接口


免責聲明!

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



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