使用HttpClient調(diào)用接口的實(shí)例講解
一,編寫返回對象
public class HttpResult { // 響應(yīng)的狀態(tài)碼 private int code; // 響應(yīng)的響應(yīng)體 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,相當(dāng)于打開瀏覽器 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è)置參數(shù) uriBuilder.setParameter(entry.getKey(), entry.getValue().toString()); } } // 2 創(chuàng)建httpGet對象,相當(dāng)于設(shè)置url請求地址 HttpGet httpGet = new HttpGet(uriBuilder.build()); // 3 使用HttpClient執(zhí)行httpGet,相當(dāng)于按回車,發(fā)起請求 CloseableHttpResponse response = this.httpClient.execute(httpGet); // 4 解析結(jié)果,封裝返回對象httpResult,相當(dāng)于顯示相應(yīng)的結(jié)果 // 狀態(tài)碼 // response.getStatusLine().getStatusCode(); // 響應(yīng)體,字符串,如果response.getEntity()為空,下面這個(gè)代碼會報(bào)錯(cuò),所以解析之前要做非空的判斷 // 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è)置參數(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"); // 把表單對象設(shè)置到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(), ""); } // 返回結(jié)果 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è)置參數(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"); // 把表單對象設(shè)置到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(), ""); } // 返回結(jié)果 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è)置參數(shù) uriBuilder.setParameter(entry.getKey(), entry.getValue().toString()); } } // 2 創(chuàng)建httpGet對象,相當(dāng)于設(shè)置url請求地址 HttpDelete httpDelete = new HttpDelete(uriBuilder.build()); // 3 使用HttpClient執(zhí)行httpGet,相當(dāng)于按回車,發(fā)起請求 CloseableHttpResponse response = this.httpClient.execute(httpDelete); // 4 解析結(jié)果,封裝返回對象httpResult,相當(dāng)于顯示相應(yīng)的結(jié)果 // 狀態(tài)碼 // response.getStatusLine().getStatusCode(); // 響應(yīng)體,字符串,如果response.getEntity()為空,下面這個(gè)代碼會報(bào)錯(cuò),所以解析之前要做非空的判斷 // 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; } }
三,調(diào)用接口
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風(fēng)格的接口&price=1000&num=1&cid=888&status=1 map.put("title", "測試APIService調(diào)用新增接口"); 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風(fēng)格的接口&price=1000&num=1&cid=888&status=1 map.put("title", "測試APIService調(diào)用修改接口"); 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調(diào)用接口的實(shí)例講解就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
MyBatis-Plus中公共字段的統(tǒng)一處理的實(shí)現(xiàn)
在開發(fā)中經(jīng)常遇到多個(gè)實(shí)體類有共同的屬性字段,這些字段屬于公共字段,本文主要介紹了MyBatis-Plus中公共字段的統(tǒng)一處理的實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的可以了解一下2023-08-08Java+Selenium調(diào)用JavaScript的方法詳解
這篇文章主要為大家講解了java在利用Selenium操作瀏覽器網(wǎng)站時(shí)候,有時(shí)會需要用的JavaScript的地方,代碼該如何實(shí)現(xiàn)呢?快跟隨小編一起學(xué)習(xí)一下吧2023-01-01深入解析Java多態(tài)進(jìn)階學(xué)習(xí)
java的動(dòng)態(tài)綁定機(jī)制非常重要。這篇文章將帶大家更深入的學(xué)習(xí)一下Java的多態(tài),文中的示例代碼講解詳細(xì),對我們學(xué)習(xí)Java有一定幫助,需要的可以參考一下2022-07-07SpringBoot?@Configuration與@Bean注解使用介紹
這篇文章主要介紹了SpringBoot中的@Configuration與@Bean注解,在進(jìn)行項(xiàng)目編寫前,我們還需要知道一個(gè)東西,就是SpringBoot對我們的SpringMVC還做了哪些配置,包括如何擴(kuò)展,如何定制,只有把這些都搞清楚了,我們在之后使用才會更加得心應(yīng)手2022-10-10Spring 靜態(tài)變量/構(gòu)造函數(shù)注入失敗的解決方案
我們經(jīng)常會遇到一下問題:Spring對靜態(tài)變量的注入為空、在構(gòu)造函數(shù)中使用Spring容器中的Bean對象,得到的結(jié)果為空。不要擔(dān)心,本文將為大家介紹如何解決這些問題,跟隨小編來看看吧2021-11-11SpringCloud?Feign實(shí)現(xiàn)微服務(wù)之間相互請求問題
Feign是Netflix開發(fā)的聲明式、模板化的HTTP客戶端,?Feign可以幫助我們更快捷、優(yōu)雅地實(shí)現(xiàn)微服務(wù)之間的調(diào)用,這篇文章主要介紹了SpringCloud?Feign實(shí)現(xiàn)微服務(wù)之間相互請求,需要的朋友可以參考下2022-06-06手把手帶你理解java線程池之工作隊(duì)列workQueue
這篇文章主要介紹了java線程池之工作隊(duì)列workQueue,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-09-09