最近要在项目中调用别人提供的接口服务,网上大概搜了一下,发现除了传统的httpclient之外,Spring也为我们提供了一个非常方便的HTTP客户端,允许我们调用各种rest服务,包括GET,POST,PUT,DELETE等等。折腾了一下发现还挺好用的,下面贴出RestTemplate发送GET和POST的示例代码。
配置类:
package com.test.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
/**
* @description:
* @author: myp
* @create: 2019-08-05 13:44
**/
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory){
return new RestTemplate(factory);
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
//设置连接超时
factory.setConnectTimeout(15000);
factory.setReadTimeout(5000);
return factory;
}
}
GET请求:
package com.test.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;
/**
* @description:
* @author: myp
* @create: 2019-09-16 13:43
**/
public class TestRest {
@Autowired
private RestTemplate restTemplate;
public static void main(String[] args) {
Map<String,Object> param = new HashMap<>();
param.put("param1", "1");
param.put("param2", "2");
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", token);
ResponseEntity<Map> response = restTemplate.exchange(
"http://api.test.com?param1={param1}¶m2={param2}",
HttpMethod.GET,
new HttpEntity<String>(headers),
Map.class,
param);
Map<Object,Object> body = response.getBody();
}
}
其中,exchange方法参数分别为:
- 请求的url,其中{}为参数占位符,分别对应请求参数map中的key.
- 请求方法.
- 请求实体,可以封装请求体和请求头.
- 返回体转换的类型,这里返回json,将其指定为Map.
- 请求参数map.
关于返回数据的说明:如果你返回的为一个复杂json,只需要按照以下原则,一个json对象对应一个LinkedHashMap<Object,Object>,key为属性名,value为对应的值,如果返回的是一个json对象数组,那么对应一个List<LinkedHashMap<Object,Object>>.
POST请求:
public Result testPost(PostEntity postEntity,String token) {
MediaType type = MediaType.parseMediaType("application/json");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(type);
headers.add("Accept", MediaType.ALL_VALUE);
headers.add("Authorization", token);
JSONObject param = JSONUtil.parseObj(postEntity);
HttpEntity<String> formEntity = new HttpEntity<String>(param.toString(), headers);
ResponseEntity<Integer> responsebody = restTemplate.exchange(
saveLeaseContractUrl,
HttpMethod.POST,
formEntity,
Integer.class);
Integer contractId = responsebody.getBody();
其中exchange的参数基本相同,只是请求参数此时被放在了请求体中,就是这里的formEntity,一个请求体,一个是请求头。
因为我们请求参数是一个json对象,所以这里设置ContentType设置为json格式, headers.add("Accept", MediaType.ALL_VALUE)为设置返回格式的请求头。