使用HttpClient調用介面,httpclient調用介面

來源:互聯網
上載者:User

使用HttpClient調用介面,httpclient調用介面

一,編寫返回對象

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

// 響應的響應體
private String body;
get/set…
}

二,封裝HttpClient

package cn.xxxxxx.httpclient;import java.util.ArrayList;import java.util.List;import java.util.Map;import org.apache.http.NameValuePair;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpDelete;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.client.methods.HttpPut;import org.apache.http.client.utils.URIBuilder;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;public class APIService {    private CloseableHttpClient httpClient;    public APIService() {        // 1 建立HttpClinet,相當於開啟瀏覽器        this.httpClient = HttpClients.createDefault();    }    /**     * 帶參數的get請求     *      * @param url     * @param map     * @return     * @throws Exception     */    public 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 = this.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 HttpResult doGet(String url) throws Exception {        HttpResult httpResult = this.doGet(url, null);        return httpResult;    }    /**     * 帶參數的post請求     *      * @param url     * @param map     * @return     * @throws Exception     */    public HttpResult doPost(String url, Map<String, Object> map) throws Exception {        // 聲明httpPost請求        HttpPost httpPost = new HttpPost(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中            httpPost.setEntity(formEntity);        }        // 使用HttpClient發起請求,返回response        CloseableHttpResponse response = this.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 HttpResult doPost(String url) throws Exception {        HttpResult httpResult = this.doPost(url, null);        return httpResult;    }    /**     * 帶參數的Put請求     *      * @param url     * @param map     * @return     * @throws Exception     */    public 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 = this.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 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 = this.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;    }}

 

三,調用介面

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 {    private APIService apiService;    @Before    public void init() {        this.apiService = new APIService();    }    // 查詢    @Test    public void testQueryItemById() throws Exception {        // http://manager.aaaaaa.com/rest/item/interface/{id}        String url = "http://manager.aaaaaa.com/rest/item/interface/42";        HttpResult httpResult = this.apiService.doGet(url);        System.out.println(httpResult.getCode());        System.out.println(httpResult.getBody());    }    // 新增    @Test    public void testSaveItem() throws Exception {        // http://manager.aaaaaa.com/rest/item/interface/{id}        String url = "http://manager.aaaaaa.com/rest/item/interface";        Map<String, Object> map = new HashMap<String, Object>();        // title=測試RESTful風格的介面&price=1000&num=1&cid=888&status=1        map.put("title", "測試APIService調用新增介面");        map.put("price", "1000");        map.put("num", "1");        map.put("cid", "666");        map.put("status", "1");        HttpResult httpResult = this.apiService.doPost(url, map);        System.out.println(httpResult.getCode());        System.out.println(httpResult.getBody());    }    // 修改    @Test    public void testUpdateItem() throws Exception {        // http://manager.aaaaaa.com/rest/item/interface/{id}        String url = "http://manager.aaaaaa.com/rest/item/interface";        Map<String, Object> map = new HashMap<String, Object>();        // title=測試RESTful風格的介面&price=1000&num=1&cid=888&status=1        map.put("title", "測試APIService調用修改介面");        map.put("id", "44");        HttpResult httpResult = this.apiService.doPut(url, map);        System.out.println(httpResult.getCode());        System.out.println(httpResult.getBody());    }    // 刪除    @Test    public void testDeleteItemById() throws Exception {        // http://manager.aaaaaa.com/rest/item/interface/{id}        String url = "http://manager.aaaaaa.com/rest/item/interface/44";        HttpResult httpResult = this.apiService.doDelete(url, null);        System.out.println(httpResult.getCode());        System.out.println(httpResult.getBody());    }}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.