项目中有个地方需要请求第三方接口的数据,接口规定了post方法和对象头,打算采用RestTemplate的postForEntity方法获取数据,但是在添加请求体的时候就出问题了。(项目用的是java11)
首先查看一下postForEntity的源码:
public <T> ResponseEntity<T> postForEntity(URI url, @Nullable Object request, Class<T> responseType) throws RestClientException {
RequestCallback requestCallback = this.httpEntityCallback(request, responseType);
ResponseExtractor<ResponseEntity<T>> responseExtractor = this.responseEntityExtractor(responseType);
return (ResponseEntity)nonNull(this.execute(url, HttpMethod.POST, requestCallback, responseExtractor));
}
发现传参第二项是object类的请求数据,但是查看网上的教程都是用一个带泛型的HttpEntity类型传递的请求参数,当时就有点疑惑,干嘛非要这样传呢?
继续点进去看,一直点到实际用到request:
public <T> RequestCallback httpEntityCallback(@Nullable Object requestBody