最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用HttpClient調(diào)用接口的實(shí)例講解

 更新時(shí)間:2017年10月07日 09:55:58   作者:0001  
下面小編就為大家?guī)?lái)一篇使用HttpClient調(diào)用接口的實(shí)例講解。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧

一,編寫(xiě)返回對(duì)象

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)于打開(kāi)瀏覽器
  this.httpClient = HttpClients.createDefault();
 }

 /**
  * 帶參數(shù)的get請(qǐng)求
  * 
  * @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對(duì)象,相當(dāng)于設(shè)置url請(qǐng)求地址
  HttpGet httpGet = new HttpGet(uriBuilder.build());

  // 3 使用HttpClient執(zhí)行httpGet,相當(dāng)于按回車,發(fā)起請(qǐng)求
  CloseableHttpResponse response = this.httpClient.execute(httpGet);

  // 4 解析結(jié)果,封裝返回對(duì)象httpResult,相當(dāng)于顯示相應(yīng)的結(jié)果
  // 狀態(tài)碼
  // response.getStatusLine().getStatusCode();
  // 響應(yīng)體,字符串,如果response.getEntity()為空,下面這個(gè)代碼會(huì)報(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請(qǐng)求
  * 
  * @param url
  * @return
  * @throws Exception
  */
 public HttpResult doGet(String url) throws Exception {
  HttpResult httpResult = this.doGet(url, null);
  return httpResult;
 }

 /**
  * 帶參數(shù)的post請(qǐng)求
  * 
  * @param url
  * @param map
  * @return
  * @throws Exception
  */
 public HttpResult doPost(String url, Map<String, Object> map) throws Exception {
  // 聲明httpPost請(qǐng)求
  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表單對(duì)象
   UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "UTF-8");

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

  // 使用HttpClient發(fā)起請(qǐng)求,返回response
  CloseableHttpResponse response = this.httpClient.execute(httpPost);

  // 解析response封裝返回對(duì)象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請(qǐng)求
  * 
  * @param url
  * @return
  * @throws Exception
  */
 public HttpResult doPost(String url) throws Exception {
  HttpResult httpResult = this.doPost(url, null);
  return httpResult;
 }

 /**
  * 帶參數(shù)的Put請(qǐng)求
  * 
  * @param url
  * @param map
  * @return
  * @throws Exception
  */
 public HttpResult doPut(String url, Map<String, Object> map) throws Exception {
  // 聲明httpPost請(qǐng)求
  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表單對(duì)象
   UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "UTF-8");

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

  // 使用HttpClient發(fā)起請(qǐng)求,返回response
  CloseableHttpResponse response = this.httpClient.execute(httpPut);

  // 解析response封裝返回對(duì)象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請(qǐng)求
  * 
  * @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對(duì)象,相當(dāng)于設(shè)置url請(qǐng)求地址
  HttpDelete httpDelete = new HttpDelete(uriBuilder.build());

  // 3 使用HttpClient執(zhí)行httpGet,相當(dāng)于按回車,發(fā)起請(qǐng)求
  CloseableHttpResponse response = this.httpClient.execute(httpDelete);

  // 4 解析結(jié)果,封裝返回對(duì)象httpResult,相當(dāng)于顯示相應(yīng)的結(jié)果
  // 狀態(tài)碼
  // response.getStatusLine().getStatusCode();
  // 響應(yīng)體,字符串,如果response.getEntity()為空,下面這個(gè)代碼會(huì)報(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=測(cè)試RESTful風(fēng)格的接口&price=1000&num=1&cid=888&status=1
  map.put("title", "測(cè)試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=測(cè)試RESTful風(fēng)格的接口&price=1000&num=1&cid=888&status=1
  map.put("title", "測(cè)試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í)例講解就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Zuul 如何屏蔽服務(wù)和指定路徑

    Zuul 如何屏蔽服務(wù)和指定路徑

    這篇文章主要介紹了Zuul 如何屏蔽服務(wù)和指定路徑的實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-07-07
  • 關(guān)于SpringSecurity簡(jiǎn)介以及和Shiro的區(qū)別

    關(guān)于SpringSecurity簡(jiǎn)介以及和Shiro的區(qū)別

    這篇文章主要介紹了關(guān)于SpringSecurity簡(jiǎn)介以及和Shiro的區(qū)別,在Java應(yīng)用安全領(lǐng)域,Spring Security會(huì)成為被首先推崇的解決方案,就像我們看到服務(wù)器就會(huì)聯(lián)想到Linux一樣順理成章,需要的朋友可以參考下
    2023-07-07
  • springboot?html調(diào)用js無(wú)效400問(wèn)題及解決

    springboot?html調(diào)用js無(wú)效400問(wèn)題及解決

    這篇文章主要介紹了springboot?html調(diào)用js無(wú)效400的問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-03-03
  • Java synchronized線程交替運(yùn)行實(shí)現(xiàn)過(guò)程詳解

    Java synchronized線程交替運(yùn)行實(shí)現(xiàn)過(guò)程詳解

    這篇文章主要介紹了Java synchronized線程交替運(yùn)行實(shí)現(xiàn)過(guò)程詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-11-11
  • Java線程創(chuàng)建與Thread類的使用方法

    Java線程創(chuàng)建與Thread類的使用方法

    這篇文章主要介紹了Java線程創(chuàng)建與Thread類的使用方法,圍繞java多線程中Thread類的使用以及有關(guān)線程對(duì)象創(chuàng)建和常用方法的相關(guān)資料展開(kāi)詳細(xì)內(nèi)容,具有一定的參考價(jià)值,需要的下伙伴可以參考一下
    2022-06-06
  • MyBatis?Generator生成的$?sql是否存在注入風(fēng)險(xiǎn)詳解

    MyBatis?Generator生成的$?sql是否存在注入風(fēng)險(xiǎn)詳解

    這篇文章主要介紹了MyBatis?Generator生成的$?sql是否存在注入風(fēng)險(xiǎn)詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • Java利用redis實(shí)現(xiàn)防止接口重復(fù)提交

    Java利用redis實(shí)現(xiàn)防止接口重復(fù)提交

    本文主要為大家詳細(xì)介紹了Java如何利用redis實(shí)現(xiàn)防止接口重復(fù)提交,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-11-11
  • java 反射機(jī)制

    java 反射機(jī)制

    本文主要介紹了java反射機(jī)制的相關(guān)知識(shí),具有一定的參考價(jià)值,下面跟著小編一起來(lái)看下吧
    2017-02-02
  • java實(shí)現(xiàn)最短路徑算法之Dijkstra算法

    java實(shí)現(xiàn)最短路徑算法之Dijkstra算法

    這篇文章主要介紹了java實(shí)現(xiàn)最短路徑算法之Dijkstra算法, Dijkstra算法是最短路徑算法中為人熟知的一種,是單起點(diǎn)全路徑算法,有興趣的可以了解一下
    2017-10-10
  • SpringBoot bean依賴屬性配置詳細(xì)介紹

    SpringBoot bean依賴屬性配置詳細(xì)介紹

    Spring容器是Spring的核心,一切SpringBean都存儲(chǔ)在Spring容器內(nèi)??梢哉f(shuō)bean是spring核心中的核心。Bean配置信息定義了Bean的實(shí)現(xiàn)及依賴關(guān)系,這篇文章主要介紹了SpringBoot bean依賴屬性配置
    2022-09-09

最新評(píng)論

会同县| 新巴尔虎右旗| 钦州市| 内黄县| 阿瓦提县| 河源市| 昌江| 定州市| 行唐县| 苍山县| 新密市| 鹤壁市| 连云港市| 遂平县| 揭西县| 修文县| 喜德县| 灵寿县| 阜新| 涪陵区| 鹤壁市| 庄河市| 囊谦县| 长沙县| 静海县| 博白县| 石楼县| 开远市| 屏南县| 两当县| 封开县| 方山县| 青神县| 汾阳市| 乐业县| 浑源县| 会泽县| 福鼎市| 贞丰县| 榆社县| 建始县|