使用HttpClient調用接口的實例講解
更新時間:2017年10月07日 09:55:58 作者:0001
下面小編就為大家?guī)硪黄褂肏ttpClient調用接口的實例講解。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
一,編寫返回對象
public class HttpResult { // 響應的狀態(tài)碼 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 創(chuàng)建HttpClinet,相當于打開瀏覽器 this.httpClient = HttpClients.createDefault(); } /** * 帶參數(shù)的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); // 判斷參數(shù)map是否為非空 if (map != null) { // 遍歷參數(shù) for (Map.Entry<String, Object> entry : map.entrySet()) { // 設置參數(shù) uriBuilder.setParameter(entry.getKey(), entry.getValue().toString()); } } // 2 創(chuàng)建httpGet對象,相當于設置url請求地址 HttpGet httpGet = new HttpGet(uriBuilder.build()); // 3 使用HttpClient執(zhí)行httpGet,相當于按回車,發(fā)起請求 CloseableHttpResponse response = this.httpClient.execute(httpGet); // 4 解析結果,封裝返回對象httpResult,相當于顯示相應的結果 // 狀態(tài)碼 // response.getStatusLine().getStatusCode(); // 響應體,字符串,如果response.getEntity()為空,下面這個代碼會報錯,所以解析之前要做非空的判斷 // EntityUtils.toString(response.getEntity(), "UTF-8"); HttpResult httpResult = null; // 解析數(shù)據(jù)封裝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; } /** * 不帶參數(shù)的get請求 * * @param url * @return * @throws Exception */ public HttpResult doGet(String url) throws Exception { HttpResult httpResult = this.doGet(url, null); return httpResult; } /** * 帶參數(shù)的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) { // 聲明存放參數(shù)的List集合 List<NameValuePair> params = new ArrayList<NameValuePair>(); // 遍歷map,設置參數(shù)到list中 for (Map.Entry<String, Object> entry : map.entrySet()) { params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString())); } // 創(chuàng)建form表單對象 UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "UTF-8"); // 把表單對象設置到httpPost中 httpPost.setEntity(formEntity); } // 使用HttpClient發(fā)起請求,返回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; } /** * 不帶參數(shù)的post請求 * * @param url * @return * @throws Exception */ public HttpResult doPost(String url) throws Exception { HttpResult httpResult = this.doPost(url, null); return httpResult; } /** * 帶參數(shù)的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) { // 聲明存放參數(shù)的List集合 List<NameValuePair> params = new ArrayList<NameValuePair>(); // 遍歷map,設置參數(shù)到list中 for (Map.Entry<String, Object> entry : map.entrySet()) { params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString())); } // 創(chuàng)建form表單對象 UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "UTF-8"); // 把表單對象設置到httpPost中 httpPut.setEntity(formEntity); } // 使用HttpClient發(fā)起請求,返回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; } /** * 帶參數(shù)的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); // 判斷參數(shù)map是否為非空 if (map != null) { // 遍歷參數(shù) for (Map.Entry<String, Object> entry : map.entrySet()) { // 設置參數(shù) uriBuilder.setParameter(entry.getKey(), entry.getValue().toString()); } } // 2 創(chuàng)建httpGet對象,相當于設置url請求地址 HttpDelete httpDelete = new HttpDelete(uriBuilder.build()); // 3 使用HttpClient執(zhí)行httpGet,相當于按回車,發(fā)起請求 CloseableHttpResponse response = this.httpClient.execute(httpDelete); // 4 解析結果,封裝返回對象httpResult,相當于顯示相應的結果 // 狀態(tài)碼 // response.getStatusLine().getStatusCode(); // 響應體,字符串,如果response.getEntity()為空,下面這個代碼會報錯,所以解析之前要做非空的判斷 // EntityUtils.toString(response.getEntity(), "UTF-8"); HttpResult httpResult = null; // 解析數(shù)據(jù)封裝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()); } }
以上這篇使用HttpClient調用接口的實例講解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
MyBatis-Plus中公共字段的統(tǒng)一處理的實現(xiàn)
在開發(fā)中經(jīng)常遇到多個實體類有共同的屬性字段,這些字段屬于公共字段,本文主要介紹了MyBatis-Plus中公共字段的統(tǒng)一處理的實現(xiàn),具有一定的參考價值,感興趣的可以了解一下2023-08-08Java+Selenium調用JavaScript的方法詳解
這篇文章主要為大家講解了java在利用Selenium操作瀏覽器網(wǎng)站時候,有時會需要用的JavaScript的地方,代碼該如何實現(xiàn)呢?快跟隨小編一起學習一下吧2023-01-01SpringBoot?@Configuration與@Bean注解使用介紹
這篇文章主要介紹了SpringBoot中的@Configuration與@Bean注解,在進行項目編寫前,我們還需要知道一個東西,就是SpringBoot對我們的SpringMVC還做了哪些配置,包括如何擴展,如何定制,只有把這些都搞清楚了,我們在之后使用才會更加得心應手2022-10-10Spring 靜態(tài)變量/構造函數(shù)注入失敗的解決方案
我們經(jīng)常會遇到一下問題:Spring對靜態(tài)變量的注入為空、在構造函數(shù)中使用Spring容器中的Bean對象,得到的結果為空。不要擔心,本文將為大家介紹如何解決這些問題,跟隨小編來看看吧2021-11-11SpringCloud?Feign實現(xiàn)微服務之間相互請求問題
Feign是Netflix開發(fā)的聲明式、模板化的HTTP客戶端,?Feign可以幫助我們更快捷、優(yōu)雅地實現(xiàn)微服務之間的調用,這篇文章主要介紹了SpringCloud?Feign實現(xiàn)微服務之間相互請求,需要的朋友可以參考下2022-06-06