pom中添加依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.9</version>
</dependency>
RestTemplate,默认用的 HttpComponentsClientHttpRequestFactory 工厂,其中HttpComponentsClientHttpRequestFactory 的 createHttpUriRequest 方法,发现 GET 请求是HttpGet,HttpGet 继承 HttpRequestBase,HttpRequestBase 是不支持传递body的。
HttpEntityEnclosingRequestBase是可以传递body的,那就自定义一个工厂继承HttpComponentsClientHttpRequestFactory,重写createHttpUriRequest方法,当发送的请求是GET请求时,创建自定义的继承HttpEntityEnclosingRequestBase的类,这样GET请求就可以传送body。
public class HttpComponentsClientRestfulHttpRequestFactory extends HttpComponentsClientHttpRequestFactory {
@Override
protected HttpUriRequest createHttpUriRequest(HttpMethod httpMethod, URI uri) {
if (httpMethod == HttpMethod.GET) {
return new HttpGetRequestWithEntity(uri);
}
return super.createHttpUriRequest(httpMethod, uri);
}
}
public class HttpGetRequestWithEntity extends HttpEntityEnclosingRequestBase {
public HttpGetRequestWithEntity(final URI uri) {
super.setURI(uri);
}
@Override
public String getMethod() {
return HttpMethod.GET.name();
}
}
HttpEntity 的 httpheader 需要设置 headers.setContentType(MediaType.APPLICATION_JSON)
HttpComponentsClientRestfulHttpRequestFactory factory = new HttpComponentsClientRestfulHttpRequestFactory();
factory.setConnectTimeout(30000);
factory.setReadTimeout(60000);
this.restTemplate = new RestTemplate(factory);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> httpEntity = new HttpEntity<>(JSONObject.toJSONString(dataMap), headers);
ResponseEntity<byte[]> processEntity = restTemplate.exchange(processUri, HttpMethod.GET, httpEntity, byte[].class);