Spring-发送Http请求-RestTemplate
RestTemplate是由Spring用于同步client端的核心类,简化了与http服务的通信,统一了RESTFul的标准,封装了http连接,我们只需要传入url及其返回值类型即可。相较于之前常用的HttpClient,RestTemplate是一种更为优雅的调用RESTFul服务的方式。
1.Maven引入
pom.xml配置项
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.3.22</version>
</dependency>
2.代码展示
发送请求工具类
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import javax.annotation.PostConstruct;
public class HttpUtil {
RestTemplate restTemplate = null;
@PostConstruct
public void before() {
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
//设置连接超时时间
requestFactory.setConnectTimeout(10000);
//设置读取超时时间
requestFactory.setReadTimeout(10000);
restTemplate = new RestTemplate(requestFactory);
}
//post请求
public JSONObject doPostForm(String urlPath, Map<String,String> body) {
// 一定要设置header
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<?> request = new HttpEntity<Object>(bodyObject, headers);
ResponseEntity<String> entity = restTemplate.postForEntity(urlPath, request, String.class);
return JSONObject.parseObject(entity.getBody());
}
//Get请求
public String doGetString(String urlPath) {
HttpHeaders headers = new HttpHeaders();
HttpEntity<String> entity = new HttpEntity<>(headers);
ResponseEntity<String> exchange = restTemplate.exchange(urlPath, HttpMethod.GET, entity, String.class);
return exchange.getBody();
}
}