RestTemplate是Spring提供的用于访问Http接口的客户端,提供同步的API;在将来的Spring版本中可能会过时,将逐渐被WebClient替代。文中所使用到的软件版本:Java 1.8.0_191、SpringBoot 2.2.1.RELEASE。

1、服务端

参见Java调用Http接口(1)--编写服务端

2、调用Http接口

2.1、GET请求

    public static void get() {
try {
String requestPath = "http://localhost:8080/demo/httptest/getUser?userId=1000&userName=李白";
RestTemplate template = new RestTemplate();
//System.out.println(template.getMessageConverters());
//第二个为StringHttpMessageConverter
template.getMessageConverters().set(1, new StringHttpMessageConverter(Charset.forName("UTF-8")));
ResponseEntity<String> response = template.getForEntity(requestPath, String.class);
System.out.println("get返回状态:" + response.getStatusCode());
System.out.println("get返回结果:" + response.getBody());
} catch (Exception e) {
e.printStackTrace();
}
}

2.2、POST请求(发送键值对数据)

    public static void post() {
String requestPath = "http://localhost:8080/demo/httptest/getUser";
RestTemplate template = new RestTemplate();
template.getMessageConverters().set(1, new StringHttpMessageConverter(Charset.forName("UTF-8")));
MultiValueMap<String, String> map = new LinkedMultiValueMap <String, String>();
map.add("userId", "1000");
map.add("userName", "李白");
ResponseEntity<String> response = template.postForEntity(requestPath, map, String.class);
System.out.println("post返回状态:" + response.getStatusCode());
System.out.println("post返回结果:" + response.getBody());
}

2.3、POST请求(发送JSON数据)

    public static void post2() {
String requestPath = "http://localhost:8080/demo/httptest/addUser";
RestTemplate template = new RestTemplate();
template.getMessageConverters().set(1, new StringHttpMessageConverter(Charset.forName("UTF-8"))); String param = "{\"userId\": \"1001\",\"userName\":\"杜甫\"}";
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json");
HttpEntity<String> entity = new HttpEntity<String>(param, headers);
ResponseEntity<String> response = template.postForEntity(requestPath, entity, String.class);
System.out.println("post json返回状态:" + response.getStatusCode());
System.out.println("post json返回结果:" + response.getBody());
}

2.4、上传文件

    public static void upload() {
String requestPath = "http://localhost:8080/demo/httptest/upload";
RestTemplate template = new RestTemplate();
template.getMessageConverters().set(1, new StringHttpMessageConverter(Charset.forName("UTF-8")));
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "file/*");
HttpEntity<FileSystemResource> entity = new HttpEntity<FileSystemResource>(new FileSystemResource("d:/a.jpg"), headers); ResponseEntity<String> response = template.postForEntity(requestPath, entity, String.class);
System.out.println("upload返回状态:" + response.getStatusCode());
System.out.println("upload返回结果:" + response.getBody());
}

2.5、上传文件及发送键值对数据

    public static void mulit() {
String requestPath = "http://localhost:8080/demo/httptest/multi";
RestTemplate template = new RestTemplate();
template.getMessageConverters().set(1, new StringHttpMessageConverter(Charset.forName("UTF-8")));
MultiValueMap<String, Object> map = new LinkedMultiValueMap <String, Object>();
map.add("param1", "参数1");
map.add("param2", "参数2");
map.add("file", new FileSystemResource("d:/a.jpg"));
ResponseEntity<String> response = template.postForEntity(requestPath, map, String.class);
System.out.println("mulit返回状态:" + response.getStatusCode());
System.out.println("mulit返回结果:" + response.getBody());
}

2.6、完整例子

package com.inspur.demo.http.client;

import java.nio.charset.Charset;

import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate; /**
*
* 通过RestTemplate调用Http接口
*
*/
public class RestTemplateCase {
/**
* GET请求
*/
public static void get() {
try {
String requestPath = "http://localhost:8080/demo/httptest/getUser?userId=1000&userName=李白";
RestTemplate template = new RestTemplate();
//System.out.println(template.getMessageConverters());
//第二个为StringHttpMessageConverter
template.getMessageConverters().set(1, new StringHttpMessageConverter(Charset.forName("UTF-8")));
ResponseEntity<String> response = template.getForEntity(requestPath, String.class);
System.out.println("get返回状态:" + response.getStatusCode());
System.out.println("get返回结果:" + response.getBody());
} catch (Exception e) {
e.printStackTrace();
}
} /**
* POST请求(发送键值对数据)
*/
public static void post() {
String requestPath = "http://localhost:8080/demo/httptest/getUser";
RestTemplate template = new RestTemplate();
template.getMessageConverters().set(1, new StringHttpMessageConverter(Charset.forName("UTF-8")));
MultiValueMap<String, String> map = new LinkedMultiValueMap <String, String>();
map.add("userId", "1000");
map.add("userName", "李白");
ResponseEntity<String> response = template.postForEntity(requestPath, map, String.class);
System.out.println("post返回状态:" + response.getStatusCode());
System.out.println("post返回结果:" + response.getBody());
} /**
* POST请求(发送json数据)
*/
public static void post2() {
String requestPath = "http://localhost:8080/demo/httptest/addUser";
RestTemplate template = new RestTemplate();
template.getMessageConverters().set(1, new StringHttpMessageConverter(Charset.forName("UTF-8"))); String param = "{\"userId\": \"1001\",\"userName\":\"杜甫\"}";
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json");
HttpEntity<String> entity = new HttpEntity<String>(param, headers);
ResponseEntity<String> response = template.postForEntity(requestPath, entity, String.class);
System.out.println("post json返回状态:" + response.getStatusCode());
System.out.println("post json返回结果:" + response.getBody());
} /**
* 上传文件
*/
public static void upload() {
String requestPath = "http://localhost:8080/demo/httptest/upload";
RestTemplate template = new RestTemplate();
template.getMessageConverters().set(1, new StringHttpMessageConverter(Charset.forName("UTF-8")));
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "file/*");
HttpEntity<FileSystemResource> entity = new HttpEntity<FileSystemResource>(new FileSystemResource("d:/a.jpg"), headers); ResponseEntity<String> response = template.postForEntity(requestPath, entity, String.class);
System.out.println("upload返回状态:" + response.getStatusCode());
System.out.println("upload返回结果:" + response.getBody());
} /**
* 上传文件及发送键值对数据
*/
public static void mulit() {
String requestPath = "http://localhost:8080/demo/httptest/multi";
RestTemplate template = new RestTemplate();
template.getMessageConverters().set(1, new StringHttpMessageConverter(Charset.forName("UTF-8")));
MultiValueMap<String, Object> map = new LinkedMultiValueMap <String, Object>();
map.add("param1", "参数1");
map.add("param2", "参数2");
map.add("file", new FileSystemResource("d:/a.jpg"));
ResponseEntity<String> response = template.postForEntity(requestPath, map, String.class);
System.out.println("mulit返回状态:" + response.getStatusCode());
System.out.println("mulit返回结果:" + response.getBody());
} public static void main(String[] args) {
get();
post();
post2();
upload();
mulit();
}
}

3、调用Https接口

与调用Http接口不一样的部分主要在设置ssl部分,设置方法是扩展SimpleClientHttpRequestFactory并在prepareConnection方法中进行ssl的设置;ssl的设置与HttpsURLConnection很相似(参见Java调用Http/Https接口(2)--HttpURLConnection/HttpsURLConnection调用Http/Https接口);下面用GET请求来演示ssl的设置,其他调用方式类似。

package com.inspur.demo.http.client;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.nio.charset.Charset;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate; import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager; import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate; import com.inspur.demo.common.util.FileUtil; /**
* 通过RestTemplate调用Https接口
*/
public class RestTemplateHttpsCase {
public static void main(String[] args) {
try {
/*
* 请求有权威证书的地址
*/
String requestPath = "https://www.baidu.com/";
RestTemplate template = new RestTemplate();
template.getMessageConverters().set(1, new StringHttpMessageConverter(Charset.forName("UTF-8")));
ResponseEntity<String> response = template.getForEntity(requestPath, String.class);
System.out.println("get1返回结果:" + response.getBody()); /*
* 请求自定义证书的地址
*/
//获取信任证书库
KeyStore trustStore = getkeyStore("jks", "d:/temp/cacerts", "123456"); //不需要客户端证书
requestPath = "https://10.40.x.x:9010/zsywservice";
template = new RestTemplate(new HttpsClientRequestFactory(trustStore));
template.getMessageConverters().set(1, new StringHttpMessageConverter(Charset.forName("UTF-8")));
response = template.getForEntity(requestPath, String.class);
System.out.println("get2返回结果:" + response.getBody()); //需要客户端证书
requestPath = "https://10.40.x.x:9016/zsywservice";
KeyStore keyStore = getkeyStore("pkcs12", "d:/client.p12", "123456");
template = new RestTemplate(new HttpsClientRequestFactory(keyStore, "123456", trustStore));
template.getMessageConverters().set(1, new StringHttpMessageConverter(Charset.forName("UTF-8")));
response = template.getForEntity(requestPath, String.class);
System.out.println("get3返回结果:" + response.getBody());
} catch (Exception e) {
e.printStackTrace();
}
} /**
* 获取证书
* @return
*/
private static KeyStore getkeyStore(String type, String filePath, String password) {
KeyStore keySotre = null;
FileInputStream in = null;
try {
keySotre = KeyStore.getInstance(type);
in = new FileInputStream(new File(filePath));
keySotre.load(in, password.toCharArray());
} catch (Exception e) {
e.printStackTrace();
} finally {
FileUtil.close(in);
}
return keySotre;
} /**
* 扩展SimpleClientHttpRequestFactory以支持Https
*/
private static class HttpsClientRequestFactory extends SimpleClientHttpRequestFactory {
private KeyStore keyStore;
private String keyStorePassword;
private KeyStore trustStore; public HttpsClientRequestFactory(KeyStore keyStore, String keyStorePassword, KeyStore trustStore) {
this.keyStore = keyStore;
this.keyStorePassword = keyStorePassword;
this.trustStore = trustStore;
} public HttpsClientRequestFactory(KeyStore trustStore) {
this.trustStore = trustStore;
} @Override
protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
try {
if (!(connection instanceof HttpsURLConnection)) {
throw new RuntimeException("An instance of HttpsURLConnection is expected");
}
HttpsURLConnection httpsConnection = (HttpsURLConnection) connection; KeyManager[] keyManagers = null;
TrustManager[] trustManagers = null;
if (this.keyStore != null) {
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
keyManagers = keyManagerFactory.getKeyManagers();
}
if (this.trustStore != null) {
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
trustManagerFactory.init(trustStore);
trustManagers = trustManagerFactory.getTrustManagers();
} else {
trustManagers = new TrustManager[] { new DefaultTrustManager()};
} SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagers, trustManagers, null);
httpsConnection.setSSLSocketFactory(sslContext.getSocketFactory());
//验证URL的主机名和服务器的标识主机名是否匹配
httpsConnection.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslSession) {
//if ("xxx".equals(hostname)) {
// return true;
//} else {
// return false;
//}
return true;
}
}); super.prepareConnection(httpsConnection, httpMethod);
} catch (Exception e) {
e.printStackTrace();
}
}
} private static final class DefaultTrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
} @Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
} @Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
}

4、AsyncRestTemplate

该模板已过时,建议使用WebClient替代。

Java调用Http/Https接口(6)--RestTemplate调用Http/Https接口的更多相关文章

  1. Java WebService接口生成和调用 图文详解>【转】【待调整】

    webservice简介: Web Service技术, 能使得运行在不同机器上的不同应用无须借助附加的.专门的第三方软件或硬件, 就可相互交换数据或集成.依据Web Service规范实施的应用之间 ...

  2. c#代码 天气接口 一分钟搞懂你的博客为什么没人看 看完python这段爬虫代码,java流泪了c#沉默了 图片二进制转换与存入数据库相关 C#7.0--引用返回值和引用局部变量 JS直接调用C#后台方法(ajax调用) Linq To Json SqlServer 递归查询

    天气预报的程序.程序并不难. 看到这个需求第一个想法就是只要找到合适天气预报接口一切都是小意思,说干就干,立马跟学生沟通价格. ​ ​不过谈报价的过程中,差点没让我一口老血喷键盘上,话说我们程序猿的人 ...

  3. java通过HttpClient方式和HttpURLConnection方式调用WebService接口

    1.引入maven依赖: <dependency> <groupId>org.apache.httpcomponents</groupId> <artifac ...

  4. java接口对接——别人调用我们接口获取数据

    java接口对接——别人调用我们接口获取数据,我们需要在我们系统中开发几个接口,给对方接口规范文档,包括访问我们的接口地址,以及入参名称和格式,还有我们的返回的状态的情况, 接口代码: package ...

  5. .net WebServer示例及调用(接口WSDL动态调用 JAVA)

    新建.asmx页面 using System; using System.Collections.Generic; using System.Linq; using System.Web; using ...

  6. 从Java future 到 Guava ListenableFuture实现异步调用

    从Java future 到 Guava ListenableFuture实现异步调用 置顶 2016年04月24日 09:11:14 皮斯特劳沃 阅读数:17570 标签: java异步调用线程非阻 ...

  7. 使用Socket&反射&Java流操作进行方法的远程调用(模拟RPC远程调用)

    写在前面 阅读本文首先得具备基本的Socket.反射.Java流操作的基本API使用知识:否则本文你可能看不懂... 服务端的端口监听 进行远程调用,那就必须得有客户端和服务端.服务端负责提供服务,客 ...

  8. java多态的实现原理(JVM调用过程)(综合多篇文章,参考见文末)

    一个对象变量可以指示多种实际类型的现象称为多态 允许不同类的对象对同一消息做出响应.方法的重载.类的覆盖正体现了多态. 1.多态的机制 1.1 本质上多态分两种 1.编译时多态(又称静态多态) 2.运 ...

  9. Atitit java c# php c++ js跨语言调用matlab实现边缘检测等功能attilax总结

    Atitit java c# php c++ js跨语言调用matlab实现边缘检测等功能attilax总结 1.1. 边缘检测的基本方法Canny最常用了1 1.2. 编写matlab边缘检测代码, ...

随机推荐

  1. Apache Kylin - 大数据下的OLAP解决方案

    OLAPCube是一种典型的多维数据分析技术,Cube本身可以认为是不同维度数据组成的dataset,一个OLAP Cube 可以拥有多个维度(Dimension),以及多个事实(Factor Mea ...

  2. Seq2Seq模型 与 Attention 策略

    Seq2Seq模型 传统的机器翻译的方法往往是基于单词与短语的统计,以及复杂的语法结构来完成的.基于序列的方式,可以看成两步,分别是 Encoder 与 Decoder,Encoder 阶段就是将输入 ...

  3. iis php web.config处理404,500等,跳转友好页面,显示500错误信息

    显示500错误信息<pre name="code" class="html"><?xml version="1.0" en ...

  4. wx.request 请求与django

    wx.request 1.wx.request相当于ajax请求,和django后台进行交互 官方文档:https://developers.weixin.qq.com/miniprogram/dev ...

  5. SNF快速开发平台2019-权限管理模型-记录级-字段级权限实践

    1.1.1  字段级权限 字段级权限适用于对不同人的能否查看或录入不同表不同字段的权限控制. 是否启用字段级权限配置 不启用字段级权限后,[用户权限管理]程序[字段级权限]按钮会隐藏,导致无法给管理其 ...

  6. 【专】linux nameserver导致的故障

    前言: 大家都知道linux下添加dns服务器,修改/etc/resolv.conf,添加nameserver 119.29.29.29这样一行即可.但是胡乱添加nameserver也会导致故障 ,此 ...

  7. a simple machine learning system demo, for ML study.

    Machine Learning System introduction This project is a full stack Django/React/Redux app that uses t ...

  8. Linux命令-nohup和&

    基础 在linux终端或控制台上执行命令时,可能不希望脚本占住屏幕需要在后台执行脚本,有几种方法让脚本在后台执行: & 当在前台运行某个作业时,终端被该作业占据:可以在命令后面加上& ...

  9. Linux(CentOS)启动时自动执行脚本(rc.local)

    一.Linux开机启动有多种方法,比如我设置mysql开机启动为:chkconfig --level 35 mysqld on 二.下面说说通过rc.local文件进行开机启动: 1.首先创建一个启动 ...

  10. JDK8:Lambda根据 单个字段、多个字段,分组求和

    使用lambda表达式分别 根据 单个字段.多个字段,分组求和 示意图: 1.根据 单个字段,分组求和:根据2019这个字段,计算一个list集合里,同属于2019的某个字段累加和 2.根据 多个字段 ...