文章目录
- SpringBoot访问外部接口
- 模拟服务接口
- RestTemplate
- pom.xml
- RestTemplateConfig
- ClientTestRestTemplateController.java
- 结果
- WebClient
- pom.xml
- ClientTestWebClientController.java
- 结果
- HttpClient
- pom.xml
- ClientTestHttpClientController.java
- 结果
- OkHttp
- pom.xml
- ClientTestOkHttpController.java
- 结果
SpringBoot访问外部接口
模拟服务接口
package com.sin.controller;import org.springframework.web.bind.annotation.*;import java.util.HashMap;
import java.util.Map;/*** @createTime 2023/12/20 9:25* @createAuthor SIN* @use*/
@RestController
@RequestMapping("/service")
public class ServiceTestController {private Map serviceMap = new HashMap();@GetMapping("/getData")public Map getServiceMap() {return serviceMap;}@PostMapping("/setData")public String setServiceMap(@RequestBody Map serviceMap) {this.serviceMap = serviceMap;return "添加成功";}}
RestTemplate
RestTemplate
是Spring提供的一个HTTP客户端,可以用来发送HTTP请求并处理响应。
pom.xml
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
RestTemplateConfig
package com.sin.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;/*** @createTime 2023/12/20 9:32* @createAuthor SIN* @use*/
@Configuration
public class RestTemplateConfig {// 注册RestTemplate实例为bean@Beanpublic RestTemplate restTemplate(ClientHttpRequestFactory factory){return new RestTemplate(factory);}// 注册ClientHttpRequestFactory实例为bean@Beanpublic ClientHttpRequestFactory clientHttpRequestFactory(){// 创建SimpleClientHttpRequestFactory实例SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();// 设置读取超时时间为5000毫秒factory.setReadTimeout(5000);// 设置连接超时时间为5000毫秒factory.setConnectTimeout(5000);return factory;}
}
ClientTestRestTemplateController.java
package com.sin.controller;import com.sin.config.RestTemplateConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;import java.util.HashMap;
import java.util.Map;/*** @createTime 2023/12/20 9:31* @createAuthor SIN* @use 使用RestTemplate来发送HTTP请求*/
@RestController
public class ClientTestRestTemplateController {@Autowiredprivate RestTemplate restTemplate;/*** 调用url路径添加数据* @return 返回发送请求后的响应结果,作为HTTP响应返回给客户端。*/@GetMapping("/addData")public String addData(){// 指定要发送POST请求的目标url路径String url = "http://localhost:8080/service/setData";// 添加数据Map map = new HashMap();map.put("id",1);map.put("name","张三");// 使用postForObject来发送POST请求(目标url,请求体参数,以字符串形式相应)return restTemplate.postForObject(url,map,String.class);}
}
结果
未添加数据之前
添加数据
添加数据之后
WebClient
RestTemplate有可能在未来的版本中被弃用,WebClient
是Spring 5中新增的一个HTTP客户端,支持异步调用和响应式编程等特性,来代替RestTemplate
pom.xml
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.62</version>
</dependency>
ClientTestWebClientController.java
package com.sin.controller;import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.HashMap;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;/*** @createTime 2023/12/20 9:54* @createAuthor SIN* @use*/
@RestController
public class ClientTestWebClientController {@GetMapping("/addData")public Object addData(){// 指定要发送POST请求的目标url路径String url = "http://localhost:8080/service/setData";// 添加数据Map map = new HashMap();map.put("name","sin");// 添加数据转换为json数据String requestJson = JSON.toJSONString(map);// 异步单值容器Mono mono = WebClient// 创建webClient实例.create()// post请求.post()// 请求的url路径.uri(url)// 指定请求的为json.contentType(MediaType.APPLICATION_JSON)// 请求参数.bodyValue(requestJson)// 获取相应结果.retrieve()// 将结果转换为String类型.bodyToMono(String.class);// 获取异步结果return mono.block();}
}
结果
未添加数据之前
添加数据
添加数据之后
HttpClient
HttpClient
是Apache的一个开源HTTP客户端,可以用来发送HTTP请求并处理响应。虽然不是Spring提供的组件,但可以与Spring集成使用。
pom.xml
<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.13</version>
</dependency>
ClientTestHttpClientController.java
package com.sin.controller;import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/*** @createTime 2023/12/20 11:02* @createAuthor SIN* @use*/
@RestController
public class ClientTestHttpClientController {@GetMapping("/addData")public String addData() throws IOException {// 创建HttpClient对象HttpClient httpClient = HttpClientBuilder.create().build();// 创建HttpPost对象,并设置URLHttpPost httpPost = new HttpPost("http://localhost:8080/service/setData");// 添加Header信息httpPost.addHeader("Content-Type", "application/json");// 创建Map数据Map<String, Object> data = new HashMap<>();data.put("name", "张三");data.put("age", 20);// 将Map数据转换为JSON格式String json = new ObjectMapper().writeValueAsString(data);// 创建StringEntity对象,并将JSON数据作为参数传入StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);// 设置请求体httpPost.setEntity(entity);// 发送POST请求HttpResponse response = httpClient.execute(httpPost);// 获取响应实体HttpEntity responseEntity = response.getEntity();// 打印响应结果String result = EntityUtils.toString(responseEntity);return result;}
}
结果
未添加数据之前
添加数据
添加数据之后
OkHttp
OkHttp
是Square公司开发的一个高性能的HTTP客户端,具有连接池、缓存、拦截器等功能。虽然不是Spring提供的组件,但可以与Spring集成使用。
pom.xml
<dependency><groupId>com.squareup.okhttp3</groupId><artifactId>okhttp</artifactId><version>4.9.1</version>
</dependency>
ClientTestOkHttpController.java
package com.sin.controller;import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;import java.io.IOException;
import java.util.HashMap;
import java.util.Map;/*** @createTime 2023/12/20 11:10* @createAuthor SIN* @use*/
@RestController
public class ClientTestOkHttpController {@GetMapping("/addData")public String addData() throws IOException {// 创建OkHttpClient对象OkHttpClient client = new OkHttpClient();// 创建Map数据Map<String, Object> data = new HashMap<>();data.put("1", 1);data.put("2", 2);// 将Map数据转换为JSON格式String json = new ObjectMapper().writeValueAsString(data);// 设置请求体RequestBody body = RequestBody.create(json, MediaType.parse("application/json"));// 创建Request对象,并设置URL和请求体Request request = new Request.Builder().url("http://localhost:8080/service/setData").post(body).build();// 发送请求并获取响应Response response = client.newCall(request).execute();// 获取响应结果String result = response.body().string();return result;}
}
结果
未添加数据之前
添加数据
添加数据之后