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

所属分类: 软件编程 / java 阅读数: 22
收藏 0 赞 0 分享

一,编写返回对象

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调用接口的实例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

更多精彩内容其他人还在看

Java的面向对象编程基本概念学习笔记整理

这篇文章主要介绍了Java的面向对象编程基本概念学习笔记整理,包括类与方法以及多态等支持面向对象语言中的重要特点,需要的朋友可以参考下
收藏 0 赞 0 分享

Eclipse下编写java程序突然不会自动生成R.java文件和包的解决办法

这篇文章主要介绍了Eclipse下编写java程序突然不会自动生成R.java文件和包的解决办法 的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享

基于Java实现杨辉三角 LeetCode Pascal's Triangle

这篇文章主要介绍了基于Java实现杨辉三角 LeetCode Pascal's Triangle的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享

Java中Spring获取bean方法小结

Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器框架,如何在程序中获取Spring配置的bean呢?下面通过本文给大家介绍Java中Spring获取bean方法小结,对spring获取bean方法相关知识感兴趣的朋友一起学习吧
收藏 0 赞 0 分享

如何计算Java对象占用了多少空间?

在Java中没有sizeof运算符,所以没办法知道一个对象到底占用了多大的空间,但是在分配对象的时候会有一些基本的规则,我们根据这些规则大致能判断出来对象大小,需要的朋友可以参考下
收藏 0 赞 0 分享

剖析Java中的事件处理与异常处理机制

这篇文章主要介绍了Java中的事件处理与异常处理机制,讲解Java是如何对事件或者异常作出响应以及定义异常的一些方法,需要的朋友可以参考下
收藏 0 赞 0 分享

详解Java的Struts2框架的结构及其数据转移方式

这篇文章主要介绍了详解Java的Struts2框架的结构及其数据转移方式,Struts框架是Java的SSH三大web开发框架之一,需要的朋友可以参考下
收藏 0 赞 0 分享

Java封装好的mail包发送电子邮件的类

本文给大家分享了2个java封装好的mail包发送电子邮件的类,并附上使用方法,小伙伴们可以根据自己的需求自由选择。
收藏 0 赞 0 分享

在Java的Struts中判断是否调用AJAX及用拦截器对其优化

这篇文章主要介绍了在Java的Struts中判断是否调用AJAX及用拦截器对其优化的方法,Struts框架是Java的SSH三大web开发框架之一,需要的朋友可以参考下
收藏 0 赞 0 分享

java多线程Future和Callable类示例分享

JAVA多线程实现方式主要有三种:继承Thread类、实现Runnable接口、使用ExecutorService、Callable、Future实现有返回结果的多线程。其中前两种方式线程执行完后都没有返回值,只有最后一种是带返回值的。今天我们就来研究下Future和Callab
收藏 0 赞 0 分享
查看更多