有的时候,我们的 Spring Boot 应用需要调用第三方接口,这个接口可能是 Http协议、可能是 WebService、可能是 FTP或其他格式,本章讨论 Http 接口的调用。

通常基于 Http/Https 协议的接口请求动作 POST/GET/PUT/DELETE/PATCH 操作。交互的内容可以是文本、Json 或 Xml。

在 Spring Boot 中使用 Apache HttpClient 类库能够方便快捷地解决 Http 调用问题。

本项目源码 github 下载

1 新建 Spring Boot Maven 示例工程项目

注意:是用来 IDEA 开发工具

  1. File > New > Project,如下图选择 Spring Initializr 然后点击 【Next】下一步
  2. 填写 GroupId(包名)、Artifact(项目名) 即可。点击 下一步

    groupId=com.fishpro

    artifactId=httpclient
  3. 选择依赖 Spring Web Starter 前面打钩。
  4. 项目名设置为 spring-boot-study-httpclient.

2 引入依赖 Pom

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

3 编写 HttpClient 代码示例

3.1 传统的 get/post

大多数情况,第三方提供的接口都是基于 GET/POST,而且一般需要设定 url、http head 的值,所以我们下面的代码是针对只有 GET/POST 的接口设定

/**
* 传统的 http get/post 实现
* */
public class HttpClientUtils {
/**
* http get
* @param url 可带参数的 url 链接
* @param heads http 头信息
* */
public String get(String url,Map<String,String> heads){
org.apache.http.client.HttpClient httpClient= HttpClients.createDefault();
HttpResponse httpResponse = null;
String result="";
HttpGet httpGet=new HttpGet(url);
if(heads!=null){
Set<String> keySet=heads.keySet();
for(String s:keySet){
httpGet.addHeader(s,heads.get(s));
}
} try{ httpResponse=httpClient.execute(httpGet);
HttpEntity httpEntity=httpResponse.getEntity();
if(httpEntity!=null){
result= EntityUtils.toString(httpEntity,"utf-8"); } }catch (IOException e){
e.printStackTrace(); }
return result;
} /**
* http post
* */
public static String post(String url, String data, Map<String, String> heads){ org.apache.http.client.HttpClient httpClient= HttpClients.createDefault(); HttpResponse httpResponse = null;
String result=""; HttpPost httpPost=new HttpPost(url);
if(heads!=null){
Set<String> keySet=heads.keySet();
for(String s:keySet){
httpPost.addHeader(s,heads.get(s));
}
} try{
StringEntity s=new StringEntity(data,"utf-8");
httpPost.setEntity(s);
httpResponse=httpClient.execute(httpPost);
HttpEntity httpEntity=httpResponse.getEntity();
if(httpEntity!=null){
result= EntityUtils.toString(httpEntity,"utf-8"); } }catch (IOException e){
e.printStackTrace(); }
return result; }
}

调用也非常简单


3.2 基于 REST 接口的操作方法

我们可以单独为 REST 风格接口提供方法,因为 HttpClient 为我们单独提供了针对 GET/POST/PUT/DELETE 的方法。

3.2.1 GET 方法

  1. 首先创建一个http请求 HttpGet httpGet=new HttpGet(url);
  2. 自定义一个 Response Handler
  3. 执行 httpclient.execute(请求,Handler)
  4. 处理返回
/**
* http get
* @param url 可带参数的 url 链接
* @param heads http 头信息
* */
public static String get(String url,Map<String,String> heads){
org.apache.http.client.HttpClient httpClient= HttpClients.createDefault();
HttpResponse httpResponse = null;
String result="";
HttpGet httpGet=new HttpGet(url);
if(heads!=null){
Set<String> keySet=heads.keySet();
for(String s:keySet){
httpGet.addHeader(s,heads.get(s));
}
} try{ httpResponse=httpClient.execute(httpGet);
HttpEntity httpEntity=httpResponse.getEntity();
if(httpEntity!=null){
result= EntityUtils.toString(httpEntity,"utf-8"); } }catch (IOException e){
e.printStackTrace(); }
return result;
}

3.2.2 POST 方法

  1. 首先创建一个http请求 HttpPost httpPost = new HttpPost(url);
  2. 自定义一个 Response Handler,向POST中添加数据(JSON 信息)和 Header信息
     httpPost.setHeader("Accept", "application/json");
    httpPost.setHeader("Content-type", "application/json");
  3. 执行 httpclient.execute(请求,Handler)
  4. 处理返回
 /**
* post 方法
* @param url post 的 url
* @param data 数据 application/json 的时候 为json格式
* @param heads Http Head 参数
* */
public static String post(String url,String data,Map<String,String> heads) throws IOException{
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost(url);
if(heads!=null){
Set<String> keySet=heads.keySet();
for(String s:keySet){
httpPost.addHeader(s,heads.get(s));
}
}
StringEntity stringEntity = new StringEntity(data);
httpPost.setEntity(stringEntity); System.out.println("Executing request " + httpPost.getRequestLine()); // Create a custom response handler
ResponseHandler < String > responseHandler = response -> {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
};
String responseBody = httpclient.execute(httpPost, responseHandler);
System.out.println("----------------------------------------");
System.out.println(responseBody);
return responseBody;
}
}

3.2.3 PUT 方法

  1. 首先创建一个http请求 HttpPut httpPut = new HttpPut(url);
  2. 自定义一个 Response Handler,向POST中添加数据(JSON 信息)和 Header信息
     httpPut.setHeader("Accept", "application/json");
    httpPut.setHeader("Content-type", "application/json");
  3. 执行 httpclient.execute(请求,Handler)
  4. 处理返回
/**
* put 方法
* @param url put 的 url
* @param data 数据 application/json 的时候 为json格式
* @param heads Http Head 参数
* */
public static String put(String url,String data,Map<String,String> heads) throws IOException{
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
HttpPut httpPut = new HttpPut(url);
if(heads!=null){
Set<String> keySet=heads.keySet();
for(String s:keySet){
httpPut.addHeader(s,heads.get(s));
}
}
StringEntity stringEntity = new StringEntity(data);
httpPut.setEntity(stringEntity); System.out.println("Executing request " + httpPut.getRequestLine()); // Create a custom response handler
ResponseHandler < String > responseHandler = response -> {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
};
String responseBody = httpclient.execute(httpPut, responseHandler);
System.out.println("----------------------------------------");
System.out.println(responseBody);
return responseBody;
}
}

3.2.4 DELETE 方法

  1. 首先创建一个http请求 HttpDelete httpDelete = new HttpDelete(url);
  2. 自定义一个 Response Handler
  3. 执行 httpclient.execute(请求,Handler)
  4. 处理返回
/**
* delete 方法
* @param url delete 的 url
* @param heads Http Head 参数
* */
public static String delete(String url,Map<String,String> heads) throws IOException {
try (CloseableHttpClient httpclient = HttpClients.createDefault()) { HttpDelete httpDelete = new HttpDelete(url);
if(heads!=null){
Set<String> keySet=heads.keySet();
for(String s:keySet){
httpDelete.addHeader(s,heads.get(s));
}
}
System.out.println("Executing request " + httpDelete.getRequestLine()); // Create a custom response handler
ResponseHandler < String > responseHandler = response -> {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
};
String responseBody = httpclient.execute(httpDelete, responseHandler);
System.out.println("----------------------------------------");
System.out.println(responseBody);
return responseBody;
}
}

本项目源码 github 下载


参考链接

https://www.javaguides.net/2018/10/apache-httpclient-get-post-put-and-delete-methods-example.html

Spring Boot 中使用 HttpClient 进行 POST GET PUT DELETE的更多相关文章

  1. spring boot(三):Spring Boot中Redis的使用

    spring boot对常用的数据库支持外,对nosql 数据库也进行了封装自动化. redis介绍 Redis是目前业界使用最广泛的内存数据存储.相比memcached,Redis支持更丰富的数据结 ...

  2. Spring Boot中的事务管理

    原文  http://blog.didispace.com/springboottransactional/ 什么是事务? 我们在开发企业应用时,对于业务人员的一个操作实际是对数据读写的多步操作的结合 ...

  3. Spring Boot中的注解

    文章来源:http://www.tuicool.com/articles/bQnMra 在Spring Boot中几乎可以完全弃用xml配置文件,本文的主题是分析常用的注解. Spring最开始是为了 ...

  4. 在Spring Boot中使用Https

    本文介绍如何在Spring Boot中,使用Https提供服务,并将Http请求自动重定向到Https. Https证书 巧妇难为无米之炊,开始的开始,要先取得Https证书.你可以向证书机构申请证书 ...

  5. Spring Boot中使用Swagger2构建强大的RESTful API文档

    由于Spring Boot能够快速开发.便捷部署等特性,相信有很大一部分Spring Boot的用户会用来构建RESTful API.而我们构建RESTful API的目的通常都是由于多终端的原因,这 ...

  6. Dubbo在Spring和Spring Boot中的使用

    一.在Spring中使用Dubbo 1.Maven依赖 <dependency> <groupId>com.alibaba</groupId> <artifa ...

  7. springboot(十一):Spring boot中mongodb的使用

    mongodb是最早热门非关系数据库的之一,使用也比较普遍,一般会用做离线数据分析来使用,放到内网的居多.由于很多公司使用了云服务,服务器默认都开放了外网地址,导致前一阵子大批 MongoDB 因配置 ...

  8. springboot(三):Spring boot中Redis的使用

    spring boot对常用的数据库支持外,对nosql 数据库也进行了封装自动化. redis介绍 Redis是目前业界使用最广泛的内存数据存储.相比memcached,Redis支持更丰富的数据结 ...

  9. Spring Boot中使用Swagger2构建API文档

    程序员都很希望别人能写技术文档,自己却很不愿意写文档.因为接口数量繁多,并且充满业务细节,写文档需要花大量的时间去处理格式排版,代码修改后还需要同步修改文档,经常因为项目时间紧等原因导致文档滞后于代码 ...

随机推荐

  1. 路飞-后台xadmin配置

    xadmin后台管理 安装:luffy虚拟环境下 # >: pip install https://codeload.github.com/sshwsfc/xadmin/zip/django2 ...

  2. crontab实践

    1.crontab概要 2.crontab使用 3.关键配置信息 3.1如何配置定时任务 4.注意事项 参考 https://www.cnblogs.com/keithtt/p/6946498.htm ...

  3. 每天进步一点点------Xilinx DCM

    时钟---锁相环 1.       Xilinx DCM 数字时钟管理模块(Digital Clock Manager,DCM)是基于Xilinx的其他系列器件所采用的数字延迟锁相环(DLL,Dela ...

  4. js的一些基础

    事件对象: 就是用来存储事件相关的信息 事件对象存储信息有: 事件的类别,如:click,keydown等等 点击事件的位置 点击的哪一个键 等等 用于阻止事件流,用于阻止浏览器默认动作(表单提交.a ...

  5. Jarvis OJ - 软件密码破解-1 -Writeup

    Jarvis OJ - 软件密码破解-1 -Writeup 转载请标明出处http://www.cnblogs.com/WangAoBo/p/7243801.html 记录这道题主要是想记录一下动态调 ...

  6. fileupload插件调用upload.parseRequest(request)解析得到空值问题

    得到的list长度是0,项目配置不能改变,没办法了,只能将HttpServletRequest强换成DefaultMultipartHttpServletRequest ,直接获取表单中的字段了.方法 ...

  7. 对C#单例模式的理解

    2018年11月6日       小雨 一.单例模式的定义 确保一个类只有一个实例,并提供一个全局访问点来访问这个唯一的实例,是一种对象创建型模式,有如下3个要点: 只能有一个实例 必须是自行创建这个 ...

  8. 在远程连接mysql数据库出现问题怎么办

    远程连接mysql数据库报“Communications link failure...”错误 今天在用myEclipse连接时提示:Communications link failure,Last ...

  9. Java入门学习路线目录索引

    原创 Java入门学习路线目录索引 版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明. 本文链接:https://blog.csdn.net/One_ ...

  10. power-plan如何定

    Power-Plan或者说PG如何打,这是一个仁者见仁智者见智的问题,没有一个标准的答案,因为有各种各样的影响因素.本文将列举一些可能的影响因素: 1.和design  相关 1) Utilizati ...