使用HttpClient调用接口的实例讲解

 更新时间:2017年10月07日 09:55:58   作者:0001  
下面小编就为大家带来一篇使用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());

 }

}

以上这篇使用HttpClient调用接口的实例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • Zuul 如何屏蔽服务和指定路径

    Zuul 如何屏蔽服务和指定路径

    这篇文章主要介绍了Zuul 如何屏蔽服务和指定路径的实现方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-07-07
  • 关于SpringSecurity简介以及和Shiro的区别

    关于SpringSecurity简介以及和Shiro的区别

    这篇文章主要介绍了关于SpringSecurity简介以及和Shiro的区别,在Java应用安全领域,Spring Security会成为被首先推崇的解决方案,就像我们看到服务器就会联想到Linux一样顺理成章,需要的朋友可以参考下
    2023-07-07
  • springboot html调用js无效400问题及解决

    springboot html调用js无效400问题及解决

    这篇文章主要介绍了springboot html调用js无效400的问题及解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-03-03
  • Java synchronized线程交替运行实现过程详解

    Java synchronized线程交替运行实现过程详解

    这篇文章主要介绍了Java synchronized线程交替运行实现过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-11-11
  • Java线程创建与Thread类的使用方法

    Java线程创建与Thread类的使用方法

    这篇文章主要介绍了Java线程创建与Thread类的使用方法,围绕java多线程中Thread类的使用以及有关线程对象创建和常用方法的相关资料展开详细内容,具有一定的参考价值,需要的下伙伴可以参考一下
    2022-06-06
  • MyBatis Generator生成的$ sql是否存在注入风险详解

    MyBatis Generator生成的$ sql是否存在注入风险详解

    这篇文章主要介绍了MyBatis Generator生成的$ sql是否存在注入风险详解,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-12-12
  • Java利用redis实现防止接口重复提交

    Java利用redis实现防止接口重复提交

    本文主要为大家详细介绍了Java如何利用redis实现防止接口重复提交,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-11-11
  • java 反射机制

    java 反射机制

    本文主要介绍了java反射机制的相关知识,具有一定的参考价值,下面跟着小编一起来看下吧
    2017-02-02
  • java实现最短路径算法之Dijkstra算法

    java实现最短路径算法之Dijkstra算法

    这篇文章主要介绍了java实现最短路径算法之Dijkstra算法, Dijkstra算法是最短路径算法中为人熟知的一种,是单起点全路径算法,有兴趣的可以了解一下
    2017-10-10
  • SpringBoot bean依赖属性配置详细介绍

    SpringBoot bean依赖属性配置详细介绍

    Spring容器是Spring的核心,一切SpringBean都存储在Spring容器内。可以说bean是spring核心中的核心。Bean配置信息定义了Bean的实现及依赖关系,这篇文章主要介绍了SpringBoot bean依赖属性配置
    2022-09-09

最新评论