Springboot发送http请求(使用RestTemplate)
零、关键类介绍
public class HttpEntity < T > {
public static final HttpEntity < ? > EMPTY = new HttpEntity ( ) ;
private final HttpHeaders headers;
@Nullable
private final T body;
protected HttpEntity ( ) {
this ( ( Object ) null , ( MultiValueMap ) null ) ;
}
public HttpEntity ( T body) {
this ( body, ( MultiValueMap ) null ) ;
}
public HttpEntity ( MultiValueMap < String , String > headers) {
this ( ( Object ) null , headers) ;
}
public HttpEntity ( @Nullable T body, @Nullable MultiValueMap < String , String > headers) {
this . body = body;
HttpHeaders tempHeaders = new HttpHeaders ( ) ;
if ( headers != null ) {
tempHeaders. putAll ( headers) ;
}
this . headers = HttpHeaders . readOnlyHttpHeaders ( tempHeaders) ;
}
. . . . . .
}
public class HttpHeaders implements MultiValueMap < String , String > , Serializable {
. . . . . .
}
一、包引入
import org. springframework. http. * ;
import org. springframework. util. DigestUtils ;
import org. springframework. util. LinkedMultiValueMap ;
import org. springframework. util. MultiValueMap ;
import org. springframework. web. client. RestTemplate ;
二、Get请求
RestTemplate restTemplate = new RestTemplate ( ) ;
String reqUrl = String . format ( "http://jx-bd-server04.zeus.lianjia.com:16300/scheduler/task/kill?taskId=%d&userCode=%d" , taskId, userId) ;
String response = restTemplate. getForObject ( reqUrl, String . class ) ;
三、post请求
RestTemplate restTemplate = new RestTemplate ( ) ;
HttpHeaders headers = new HttpHeaders ( ) ;
headers. setContentType ( MediaType . APPLICATION_FORM_URLENCODED) ;
MultiValueMap < String , String > body = new LinkedMultiValueMap < > ( ) ;
body. add ( "id" , "123456" ) ;
HttpEntity < MultiValueMap < String , String > > requestEntity = new HttpEntity < > ( body, headers) ;
try {
ResponseEntity < String > response = restTemplate. postForEntity ( url, requestEntity, String . class ) ;
return response. getBody ( ) ;
} catch ( Exception e) {
return e. getMessage ( ) ;
}
四、get请求,带Headers
RestTemplate restTemplate = new RestTemplate ( ) ;
HttpHeaders headers = new HttpHeaders ( ) ;
headers. add ( "appKey" , "data_quality" ) ;
headers. add ( "ts" , "1638331856505" ) ;
headers. add ( "sign" , "4a1e98c5faf2a867af5afc83d81ab2ce" ) ;
HttpEntity < String > requestEntity = new HttpEntity < > ( headers) ;
try {
ResponseEntity < String > responseEntity = restTemplate. exchange ( url, HttpMethod . GET, requestEntity, String . class ) ;
System . out. println ( responseEntity. getBody ( ) ) ;
} catch ( Exception e) {
System . out. println ( e. getMessage ( ) ) ;
}