现在你可以使用spring boot 只用两行代码来完成一个请求,并返回对象
首先,请将以下依赖项添加到pom.xml文件中:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
1:发送GET请求
@Service
public class RestService {
private final RestTemplate restTemplate;
public RestService(RestTemplateBuilder restTemplateBuilder) {
this.restTemplate = restTemplateBuilder.build();
}
public String getPostsPlainJSON() {
String url = "https://www.XXX.top";
return this.restTemplate.getForObject(url, String.class);
}
}
这里返回的是纯 JSON 字符串
我们可以使用 Jackson 轻松将 JSON 字符串转成 JSON 对象
创建模型类
public class Token implements Serializable {
private String access_token;
private String expires_in;
public String getAccess_token() {
return access_token;
}
public void setAccess_token(String access_token) {
this.access_token = access_token;
}
public String getExpires_in() {
return expires_in;
}
public void setExpires_in(String expires_in) {
this.expires_in = expires_in;
}
}
将 Token 类用作getForObject()方法中的响应类型
public Token getPostsPlainJSON() {
String url = "https://www.XXX.com";
return this.restTemplate.getForObject(url, Token.class);
2:POST请求
public SecCheck get_msgSecCheck(String content ){
String url = "https://xxx.com";
//需要上传的数据
Map<String, String> paramMap = new HashMap<>();
paramMap.put("content",content);
// 创建头信息
HttpHeaders headers = new HttpHeaders();
// 'content-type' 头信息
headers.setContentType(MediaType.APPLICATION_JSON);
// 'accept' 头信息
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
// 创建请求
HttpEntity<Map<String, String>> httpEntity = new HttpEntity<>(paramMap,headers);
// 发送请求
ResponseEntity<SecCheck> response = this.restTemplate.postForEntity(url, httpEntity, SecCheck.class);
return response.getBody();
}
3:异常处理
public Login get_code2Session(){
try{
String url = "https://xxx.com";
return this.restTemplate.getForObject(url, Login.class);
}catch (HttpStatusCodeException e){
// 原始的HTTP状态代码,例如“ 404”
System.out.println(e.getRawStatusCode());
//http状态码,例如404 NOT_FOUND
System.out.println(e.getStatusCode().toString());
// 得到响应体
System.out.println(e.getResponseBodyAsString());
//获取HTTP标头
HttpHeaders headers= e.getResponseHeaders();
System.out.println(headers.get("Content-Type"));
System.out.println(headers.get("Server"));
return null;
}
}
4:超时处理
默认情况下,RestTemplate具有无限超时。
我们可以通过使用RestTemplateBuilder类来设置连接和读取超时来更改此行为。
private final RestTemplate restTemplate;
// 设置连接和读取超时时间
public WXMapper(RestTemplateBuilder restTemplateBuilder) {
this.restTemplate = restTemplateBuilder
.setConnectTimeout(Duration.ofSeconds(6000))
.setReadTimeout(Duration.ofSeconds(6000))
.build();
}