java http调用,spring RestTemplate
一、RestTemplate是什么
环境约束:
spring-web-4.3.9.RELEASE
The
RestTemplate
is the core class for client-side access to RESTful services. It is conceptually similar to other template classes in Spring, such asJdbcTemplate
andJmsTemplate
and other template classes found in other Spring portfolio projects.RestTemplate’s behavior is customized by providing callback methods and configuring the HttpMessageConverter
used to marshal objects into the HTTP request body and to unmarshal any response back into an object. As it is common to use XML as a message format, Spring provides aMarshallingHttpMessageConverter
that uses the Object-to-XML framework that is part of theorg.springframework.oxm
package. This gives you a wide range of choices of XML to Object mapping technologies to choose from.This section describes how to use the
RestTemplate
and its associatedHttpMessageConverters
.
RestTemplate
是Spring的通过客户端访问RESTful服务端的核心类,和JdbcTemplate
、JmsTemplate
概念相似,都是Spring提供的模板类RestTemplate
的行为可以通过callback回调方法和配置HttpMessageConverter
来定制,用来把对象封装到HTTP请求体,将响应信息放到一个对象中
Invoking RESTful services in Java is typically done using a helper class such as Apache HttpComponents
HttpClient
. For common REST operations this approach is too low level as shown below.java中调用RESTful服务很典型的是使用
HttpClient
,对于常用的REST操作,这些方法属于低等级的操作
String uri = "http://example.com/hotels/1/bookings";
PostMethod post = new PostMethod(uri);
String request = // create booking request content
post.setRequestEntity(new StringRequestEntity(request));
httpClient.executeMethod(post);
if (HttpStatus.SC_CREATED == post.getStatusCode()) {
Header location = post.getRequestHeader("Location");
if (location != null) {
System.out.println("Created new booking at :" + location.getValue());
}
}
使用HttpClient
我们需要自己封装Post请求,再根据响应的状态码判断从响应中获取header和body,有时候还需要自己做json转换
RestTemplate provides higher level methods that correspond to each of the six main HTTP methods that make invoking many RESTful services a one-liner and enforce REST best practices.
RestTemplate提供更高等级的符合HTTP的6中主要方法,可以很简单的调用RESTful服务
二、创建RestTemplate
创建RestTemplate很简单,只需要new RestTemplate()
,如果使用Spring架构,将创建的RestTemplate实例通过XML或注解的方式注册到Spring容器中即可
举例:
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
RestTemplate构造方法
RestTemplate有3个构造方法,一个无参构造,两个有参构造
RestTemplate无参构造
/**
* Create a new instance of the {@link RestTemplate} using default settings.
* Default {@link HttpMessageConverter}s are initialized.
* 使用默认配置创建一个RestTemplate实例
* 默认的HttpMessageConverter集合被初始化
*/
public RestTemplate() {
this.messageConverters.add(new ByteArrayHttpMessageConverter());
this.messageConverters.add(new StringHttpMessageConverter());
this.messageConverters.add(new ResourceHttpMessageConverter());
this.messageConverters.add(new SourceHttpMessageConverter<Source>());
this.messageConverters.add(new AllEncompassingFormHttpMessageConverter());
if (romePresent) {
this.messageConverters.add(new AtomFeedHttpMessageConverter());
this.messageConverters.add(new RssChannelHttpMessageConverter());
}
if (jackson2XmlPresent) {
this.messageConverters.add(new MappingJackson2XmlHttpMessageConverter());
}
else if (jaxb2Present) {
this.messageConverters.add(new Jaxb2RootElementHttpMessageConverter());
}
/**
* 如果类路径下包含com.fasterxml.jackson.databind.ObjectMapper 和 com.fasterxml.jackson.core.JsonGenerator
* 使用jackson做http请求、响应的json转换
*/
if (jackson2Present) {
this.messageConverters.add(new MappingJackson2HttpMessageConverter());
}
else if (gsonPresent) {
this.messageConverters.add(new GsonHttpMessageConverter());
}
}
参数为ClientHttpRequestFactory的构造
/**
* Create a new instance of the {@link RestTemplate} based on the given {@link ClientHttpRequestFactory}.
* @param requestFactory HTTP request factory to use
* @see org.springframework.http.client.SimpleClientHttpRequestFactory
* @see org.springframework.http.client.HttpComponentsClientHttpRequestFactory
* 使用指定的ClientHttpRequestFactory创建一个RestTemplate实例
* requestFactory是用于创建HTTP请求的工厂,默认的实现有
* SimpleClientHttpRequestFactory、HttpComponentsClientHttpRequestFactory
* 如果没有设置默认是SimpleClientHttpRequestFactory
*/
public RestTemplate(ClientHttpRequestFactory requestFactory) {
this(); //也会调用无参构造初始化默认的messageConverters
setRequestFactory(requestFactory);
}
参数为messageConverters的构造
/**
* Create a new instance of the {@link RestTemplate} using the given list of
* {@link HttpMessageConverter} to use
* @param messageConverters the list of {@link HttpMessageConverter} to use
* @since 3.2.7
* 传入自定义的HttpMessageConverter集合,并赋值给messageConverters,之后使用自定义的HttpMessageConverter
*/
public RestTemplate(List<HttpMessageConverter<?>> messageConverters) {
Assert.notEmpty(messageConverters, "At least one HttpMessageConverter required");
this.messageConverters.addAll(messageConverters);
}
三、RestTemplate API使用
RestTemplate 4.3.9.RELEASE版本 API
HTTP Method | RestTemplate Method |
---|---|
DELETE | void delete(String url, Object... uriVariables) <br /> void delete(String url, Map<String,?> uriVariables)<br />void delete(URI url) |
GET | <T> T getForObject(String url, Class<T> responseType, Object... uriVariables)<br /><T> T getForObject(String url, Class<T> responseType, Map<String,?> uriVariables)<br /><T> T getForObject(URI url, Class<T> responseType)<br /><br /><T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Object... uriVariables)<br /><T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Map<String,?> uriVariables)<br /><T> ResponseEntity<T> getForEntity(URI url, Class<T> responseType) |
HEAD | HttpHeaders headForHeaders(String url, Object... uriVariables)<br />HttpHeaders headForHeaders(String url, Map<String,?> uriVariables)<br />HttpHeaders headForHeaders(URI url) |
OPTIONS | Set<HttpMethod> optionsForAllow(String url, Object... uriVariables)<br />Set<HttpMethod> optionsForAllow(String url, Map<String,?> uriVariables)<br />Set<HttpMethod> optionsForAllow(URI url) |
POST | <T> T postForObject(String url, Object request, Class<T> responseType, Object... uriVariables)<br /><T> T postForObject(String url, Object request, Class<T> responseType, Map<String,?> uriVariables)<br /><T> T postForObject(URI url, Object request, Class<T> responseType)<br /><br /><T> ResponseEntity<T> postForEntity(String url, Object request, Class<T> responseType, Object... uriVariables)<br /><T> ResponseEntity<T> postForEntity(String url, Object request, Class<T> responseType, Map<String,?> uriVariables)<br /><T> ResponseEntity<T> postForEntity(URI url, Object request, Class<T> responseType) |
PUT | void put(String url, Object request, Object... uriVariables)<br />void put(String url, Object request, Map<String,?> uriVariables)<br />void put(URI url, Object request) |
PATCH and others | exchange()、execute() |
-
RestTemplate的方法名遵循一定的命名规范,第一部分表示用哪种HTTP方法调用(get,post),第二部分表示返回类型
- getForObject() -- 发送GET请求,将HTTP response转换成一个指定的object对象
- postForEntity() -- 发送POST请求,将给定的对象封装到HTTP请求体,返回类型是一个HttpEntity对象
-
每个HTTP方法对应的RestTemplate方法都有3种。其中2种的url参数为字符串,URI参数变量分别是Object数组和Map,第3种使用URI类型作为参数
-
注意,使用字符串类型的url默认会对url进行转义,如
http://example.com/hotel list
在执行时会转义为http://example.com/hotel%20list
,这样其实是没有问题的,但如果字符串类型的url本身已经转义过了,执行时就会再转义一次,变成http://example.com/hotel%2520list
。如果不需要这种隐式的转义,可以使用java.net.URI
参数的方法,这种方法不会在执行时存在隐式的url转义,可以在创建URI
对象时自行决定是否转义,推荐使用UriComponentsBuilder
创建URI
UriComponents uriComponents = UriComponentsBuilder.fromUriString( "http://example.com/hotels/{hotel}/bookings/{booking}") .build() //build(true)就不会对url转义,但如果包含http://example.com/hotel list这种需要转义的url,会报错 .expand("42", "21") .encode(); URI uri = uriComponents.toUri();
-
exchange
和execute
方法比上面列出的其它方法(如getForObject、postForEntity等)使用范围更广,允许调用者指定HTTP请求的方法(GET、POST、PUT等),并且可以支持像HTTP PATCH(部分更新),但需要底层的HTTP库支持,JDK自带的HttpURLConnection
不支持PATCH方法,Apache的HTTPClient 4.2及以后版本支持
-
GET方法
getForEntity()
发送GET请求,返回ResponseEntity
/**
* 参数1: String类型 或 URI类型的请求地址
* 参数2: 指定返回的实体类型,class对象
* 参数3: uri参数,可以是变长数组或map
* 返回值:ResponseEntity<T>是Spring对HTTP响应的封装,包括了几个重要的元素,如响应码、contentType、contentLength、response header信息,response body信息等
*/
@Override
public <T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Object... uriVariables)
throws RestClientException {
RequestCallback requestCallback = acceptHeaderRequestCallback(responseType);
ResponseExtractor<ResponseEntity<T>> responseExtractor = responseEntityExtractor(responseType);
return execute(url, HttpMethod.GET, requestCallback, responseExtractor, uriVariables);
}
@Override
public <T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Map<String, ?> uriVariables)
throws RestClientException {
RequestCallback requestCallback = acceptHeaderRequestCallback(responseType);
ResponseExtractor<ResponseEntity<T>> responseExtractor = responseEntityExtractor(responseType);
return execute(url, HttpMethod.GET, requestCallback, responseExtractor, uriVariables);
}
@Override
public <T> ResponseEntity<T> getForEntity(URI url, Class<T> responseType) throws RestClientException {
RequestCallback requestCallback = acceptHeaderRequestCallback(responseType);
ResponseExtractor<ResponseEntity<T>> responseExtractor = responseEntityExtractor(responseType);
return execute(url, HttpMethod.GET, requestCallback, responseExtractor);
}
举例:
ResponseEntity<Book> responseEntity = restTemplate.getForEntity("http://127.0.0.1:8080/getbook?bookname={1}", Book.class, "java");
Book book = responseEntity.getBody(); //响应体转换为Book类型
int statusCodeValue = responseEntity.getStatusCodeValue(); //响应状态码
HttpHeaders headers = responseEntity.getHeaders(); //响应头信息
getForObject()
发送GET请求,返回指定的Object类型
/**
* 参数1: String类型 或 URI类型的请求地址
* 参数2: 指定返回的实体类型,class对象
* 参数3: uri参数,可以是变长数组或map
* 返回值:responseType指定的Object类型
*/
@Override
public <T> T getForObject(String url, Class<T> responseType, Object... uriVariables) throws RestClientException {
RequestCallback requestCallback = acceptHeaderRequestCallback(responseType);
HttpMessageConverterExtractor<T> responseExtractor =
new HttpMessageConverterExtractor<T>(responseType, getMessageConverters(), logger);
return execute(url, HttpMethod.GET, requestCallback, responseExtractor, uriVariables);
}
@Override
public <T> T getForObject(String url, Class<T> responseType, Map<String, ?> uriVariables) throws RestClientException {
RequestCallback requestCallback = acceptHeaderRequestCallback(responseType);
HttpMessageConverterExtractor<T> responseExtractor =
new HttpMessageConverterExtractor<T>(responseType, getMessageConverters(), logger);
return execute(url, HttpMethod.GET, requestCallback, responseExtractor, uriVariables);
}
@Override
public <T> T getForObject(URI url, Class<T> responseType) throws RestClientException {
RequestCallback requestCallback = acceptHeaderRequestCallback(responseType);
HttpMessageConverterExtractor<T> responseExtractor =
new HttpMessageConverterExtractor<T>(responseType, getMessageConverters(), logger);
return execute(url, HttpMethod.GET, requestCallback, responseExtractor);
}
举例:
Book book = restTemplate.getForObject("http://127.0.0.1:8080/getbook?bookname={1}", Book.class, "java");
POST方法
postForEntity()
发送POST请求,返回ResponseEntity
/**
* 参数1: String类型 或 URI类型的请求地址
* 参数2: 请求body,可以是HttpEntity类型(可设置request header),或其它Object类型
* 参数3: 指定返回的实体类型,class对象
* 参数4: uri参数,可以是变长数组或map
* 返回值:ResponseEntity<T>是Spring对HTTP响应的封装,包括了几个重要的元素,如响应码、contentType、contentLength、response header信息,response body信息等
*/
@Override
public <T> ResponseEntity<T> postForEntity(String url, Object request, Class<T> responseType, Object... uriVariables) throws RestClientException {
RequestCallback requestCallback = httpEntityCallback(request, responseType);
ResponseExtractor<ResponseEntity<T>> responseExtractor = responseEntityExtractor(responseType);
return execute(url, HttpMethod.POST, requestCallback, responseExtractor, uriVariables);
}
@Override
public <T> ResponseEntity<T> postForEntity(String url, Object request, Class<T> responseType, Map<String, ?> uriVariables) throws RestClientException {
RequestCallback requestCallback = httpEntityCallback(request, responseType);
ResponseExtractor<ResponseEntity<T>> responseExtractor = responseEntityExtractor(responseType);
return execute(url, HttpMethod.POST, requestCallback, responseExtractor, uriVariables);
}
@Override
public <T> ResponseEntity<T> postForEntity(URI url, Object request, Class<T> responseType) throws RestClientException {
RequestCallback requestCallback = httpEntityCallback(request, responseType);
ResponseExtractor<ResponseEntity<T>> responseExtractor = responseEntityExtractor(responseType);
return execute(url, HttpMethod.POST, requestCallback, responseExtractor);
}
举例:
//参数是Book类型,返回值是ResponseEntity<Book>类型
ResponseEntity<Book> responseEntity = restTemplate.postForEntity("http://127.0.0.1:8080/updateBook", book, Book.class);
Book book = responseEntity.getBody(); //响应体转换为Book类型
int statusCodeValue = responseEntity.getStatusCodeValue(); //响应状态码
HttpHeaders headers = responseEntity.getHeaders(); //响应头信息
postForObject()
发送POST请求,返回指定的Object类型
/**
* 参数1: String类型 或 URI类型的请求地址
* 参数2: 请求body,可以是HttpEntity类型(可设置request header),或其它Object类型
* 参数3: 指定返回的实体类型,class对象
* 参数4: uri参数,可以是变长数组或map
* 返回值:responseType指定的Object类型
*/
@Override
public <T> T postForObject(String url, Object request, Class<T> responseType, Object... uriVariables)
throws RestClientException {
RequestCallback requestCallback = httpEntityCallback(request, responseType);
HttpMessageConverterExtractor<T> responseExtractor =
new HttpMessageConverterExtractor<T>(responseType, getMessageConverters(), logger);
return execute(url, HttpMethod.POST, requestCallback, responseExtractor, uriVariables);
}
@Override
public <T> T postForObject(String url, Object request, Class<T> responseType, Map<String, ?> uriVariables)
throws RestClientException {
RequestCallback requestCallback = httpEntityCallback(request, responseType);
HttpMessageConverterExtractor<T> responseExtractor =
new HttpMessageConverterExtractor<T>(responseType, getMessageConverters(), logger);
return execute(url, HttpMethod.POST, requestCallback, responseExtractor, uriVariables);
}
@Override
public <T> T postForObject(URI url, Object request, Class<T> responseType) throws RestClientException {
RequestCallback requestCallback = httpEntityCallback(request, responseType);
HttpMessageConverterExtractor<T> responseExtractor =
new HttpMessageConverterExtractor<T>(responseType, getMessageConverters());
return execute(url, HttpMethod.POST, requestCallback, responseExtractor);
}
举例:
//参数是Book类型,返回值也是Book类型
Book book = restTemplate.postForObject("http://127.0.0.1:8080/updatebook", book, Book.class);
exchange方法
- 可以支持多种HTTP方法,在参数中指定
- 可以在请求中增加header和body信息,返回类型是ResponseEntity,可以从中获取响应的状态码,header和body等信息
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.set("MyRequestHeader", "MyValue");
HttpEntity requestEntity = new HttpEntity(requestHeaders);
HttpEntity<String> response = template.exchange(
"http://example.com/hotels/{hotel}",
HttpMethod.GET, //GET请求
requestEntity, //requestEntity,可以设置请求header、body
String.class, "42");
String responseHeader = response.getHeaders().getFirst("MyResponseHeader"); //响应头信息
String body = response.getBody();
四、RestTemplate扩展/配置
1、处理请求头和响应头
设置请求头信息
(1)如果是发送post、put请求,要设置请求头,可以在调用方法时的第二个参数传入HttpEntity对象,HttpEntity可以用于设置请求头信息,如
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.set("MyRequestHeader", "MyValue");
HttpEntity requestEntity = new HttpEntity(requestHeaders);
Book book = restTemplate.postForObject("http://127.0.0.1:8080/getbook", requestEntity, Book.class);
以postForObject()
方法举例,其第二个参数接收Object类型的数据,如传入的是HttpEntity,则使用它作为整个请求实体,如果传入的是其它Object类型,则将Object参数作为request body,新建一个HttpEntity作为请求实体
private HttpEntityRequestCallback(Object requestBody, Type responseType) {
super(responseType);
//如果是HttpEntity类型的,直接作为请求实体赋值给this.requestEntity
if (requestBody instanceof HttpEntity) {
this.requestEntity = (HttpEntity<?>) requestBody;
}
//如果requestBody不是HttpEntity类型,且不为空,以Object参数作为request body,并新建HttpEntity
else if (requestBody != null) {
this.requestEntity = new HttpEntity<Object>(requestBody);
}
else {
this.requestEntity = HttpEntity.EMPTY;
}
}
(2)如果是其它HTTP方法调用要设置请求头,可以使用exchange()方法,可以参考 官方示例
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.set("MyRequestHeader", "MyValue");
HttpEntity requestEntity = new HttpEntity(requestHeaders);
HttpEntity<String> response = template.exchange(
"http://example.com/hotels/{hotel}",
HttpMethod.GET, requestEntity, String.class, "42");
String responseHeader = response.getHeaders().getFirst("MyResponseHeader");
String body = response.getBody();
总之,设置request header信息,需要找到对应的restTemplate方法中可以使用HttpEntity作为参数的,提前设置好请求头信息
注意:HttpEntity有4个构造方法,无参构造,只设置请求body,只设置headers,既设置headers又设置body
/** * Create a new, empty {@code HttpEntity}. */ protected HttpEntity() { this(null, null); } /** * Create a new {@code HttpEntity} with the given body and no headers. * @param body the entity body */ public HttpEntity(T body) { this(body, null); } /** * Create a new {@code HttpEntity} with the given headers and no body. * @param headers the entity headers */ public HttpEntity(MultiValueMap<String, String> headers) { this(null, headers); } /** * Create a new {@code HttpEntity} with the given body and headers. * @param body the entity body * @param headers the entity headers */ public HttpEntity(T body, MultiValueMap<String, String> headers) { this.body = body; HttpHeaders tempHeaders = new HttpHeaders(); if (headers != null) { tempHeaders.putAll(headers); } this.headers = HttpHeaders.readOnlyHttpHeaders(tempHeaders); }
处理响应头信息
使用RestTemplate中xxxForEntity()
的方法,会返回ResponseEntity,可以从中获取到响应状态码,响应头和body等信息
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.set("MyRequestHeader", "MyValue");
HttpEntity requestEntity = new HttpEntity(requestHeaders);
HttpEntity<String> response = template.exchange(
"http://example.com/hotels/{hotel}",
HttpMethod.GET, requestEntity, String.class, "42");
//response相关信息
String responseHeader = response.getHeaders().getFirst("MyResponseHeader");
String body = response.getBody();
2、ClientHttpRequestFactory
ClientHttpRequestFactory是Spring定义的一个接口,其用于生产org.springframework.http.client.ClientHttpRequest
对象,RestTemplate只是模板类,抽象了很多调用方法,而底层真正使用何种框架发送HTTP请求是通过ClientHttpRequestFactory指定的
接口定义
/**
* Factory for {@link ClientHttpRequest} objects.
* Requests are created by the {@link #createRequest(URI, HttpMethod)} method.
* ClientHttpRequest对象的工厂
*
* @author Arjen Poutsma
* @since 3.0
*/
public interface ClientHttpRequestFactory {
/**
* Create a new {@link ClientHttpRequest} for the specified URI and HTTP method.
* <p>The returned request can be written to, and then executed by calling
* {@link ClientHttpRequest#execute()}.
* 使用指定的URI和HTTP方法新建一个ClientHttpRequest对象
* 可以修改返回的request,并通过ClientHttpRequest的execute()方法执行调用
* 即调用的逻辑也被Spring封装到ClientHttpRequest中
*
* @param uri the URI to create a request for
* @param httpMethod the HTTP method to execute
* @return the created request
* @throws IOException in case of I/O errors
*/
ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException;
}
RestTemplate可以在构造时设置ClientHttpRequestFactory,也可以通过setRequestFactory()方法设置
构造方法设置:
/**
* Create a new instance of the {@link RestTemplate} based on the given {@link ClientHttpRequestFactory}.
* @param requestFactory HTTP request factory to use
* @see org.springframework.http.client.SimpleClientHttpRequestFactory
* @see org.springframework.http.client.HttpComponentsClientHttpRequestFactory
*/
public RestTemplate(ClientHttpRequestFactory requestFactory) {
this();
setRequestFactory(requestFactory);
}
可以看到上面注释中已经给出了Spring的两种ClientHttpRequestFactory的实现类SimpleClientHttpRequestFactory
和HttpComponentsClientHttpRequestFactory
SimpleClientHttpRequestFactory
如果什么都不设置,RestTemplate默认使用的是SimpleClientHttpRequestFactory,其内部使用的是jdk的java.net.HttpURLConnection
创建底层连接,默认是没有连接池的,connectTimeout和readTimeout都是 -1,即没有超时时间
public class SimpleClientHttpRequestFactory implements ClientHttpRequestFactory, AsyncClientHttpRequestFactory {
。。。。。。
private int connectTimeout = -1;
private int readTimeout = -1;
//创建Request
@Override
public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {
HttpURLConnection connection = openConnection(uri.toURL(), this.proxy);
prepareConnection(connection, httpMethod.name());
//bufferRequestBody默认为true
if (this.bufferRequestBody) {
return new SimpleBufferingClientHttpRequest(connection, this.outputStreaming);
}
else {
return new SimpleStreamingClientHttpRequest(connection, this.chunkSize, this.outputStreaming);
}
}
/**
* Opens and returns a connection to the given URL.
* 打开并返回一个指定URL的连接
* <p>The default implementation uses the given {@linkplain #setProxy(java.net.Proxy) proxy} -
* if any - to open a connection.
* @param url the URL to open a connection to
* @param proxy the proxy to use, may be {@code null}
* @return the opened connection 返回类型为 java.net.HttpURLConnection
* @throws IOException in case of I/O errors
*/
protected HttpURLConnection openConnection(URL url, Proxy proxy) throws IOException {
URLConnection urlConnection = (proxy != null ? url.openConnection(proxy) : url.openConnection());
if (!HttpURLConnection.class.isInstance(urlConnection)) {
throw new IllegalStateException("HttpURLConnection required for [" + url + "] but got: " + urlConnection);
}
return (HttpURLConnection) urlConnection;
}
/**
* Template method for preparing the given {@link HttpURLConnection}.
* <p>The default implementation prepares the connection for input and output, and sets the HTTP method.
* @param connection the connection to prepare
* @param httpMethod the HTTP request method ({@code GET}, {@code POST}, etc.)
* @throws IOException in case of I/O errors
*/
protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
//如果connectTimeout大于等于0,设置连接超时时间
if (this.connectTimeout >= 0) {
connection.setConnectTimeout(this.connectTimeout);
}
//如果readTimeout大于等于0,设置读超时时间
if (this.readTimeout >= 0) {
connection.setReadTimeout(this.readTimeout);
}
connection.setDoInput(true);
if ("GET".equals(httpMethod)) {
connection.setInstanceFollowRedirects(true);
}
else {
connection.setInstanceFollowRedirects(false);
}
if ("POST".equals(httpMethod) || "PUT".equals(httpMethod) ||
"PATCH".equals