Spring-Send Http request-RestTemplate
RestTemplate は、Spring がクライアントを同期するために使用するコア クラスです。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();
}
}