ylbtech-Java-Class-C:org.springframework.web.client.RestTemplate
1.返回顶部
1、
org.springframework.web.client

类RestTemplate

  • 所有已实现的接口:
    RestOperations

    公共类RestTemplate
    扩展InterceptingHttpAccessor
    实现RestOperations
    同步客户端执行HTTP请求,在底层HTTP客户端库(如JDK HttpURLConnection,Apache HttpComponents 等)上公开简单的模板方法API 。

    RestTemplate通过HTTP方法提供常见方案的模板,此外还支持不太常见的案例的通用方法exchangeexecute方法。

    注意:从5.0开始,非阻塞,无效, 为同步和异步以及流方案org.springframework.web.reactive.client.WebClient提供了RestTemplate有效支持的现代替代方案。该RestTemplate 会在未来的版本中被淘汰,并没有重大的新功能的加入前进。有关更多详细信息和示例代码,请参阅Spring Framework参考文档的WebClient部分。

2、
2.返回顶部
1.1、

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;

1.2、restTemplate.getForEntity()
/**
* 接口调用凭证
* 获取小程序全局唯一后台接口调用凭据(access_token)
* https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/access-token/auth.getAccessToken.html
* @param appID 必填,小程序唯一凭证,即 AppID,可在「微信公众平台 - 设置 - 开发设置」页中获得。(需要已经成为开发者,且帐号没有异常状态)
* @param secret 必填,小程序唯一凭证密钥,即 AppSecret,获取方式同 appid
* @param restTemplate 必填
* @return
*/
public static String getAccessToken(String appID, String secret, RestTemplate restTemplate) { String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
String path = String.format("%s&appid=%s&secret=%s", url, appID, secret);
ResponseEntity<String> entity = restTemplate.getForEntity(path, String.class);
return entity.getBody();
}
1.3、restTemplate.postForEntity()
 /**
* 组合模板并添加至帐号下的个人模板库
* @param access_token 必填,接口调用凭证
* @param id 必填,模板标题id,可通过接口获取,也可登录小程序后台查看获取
* @param keyword_id_list 必填,开发者自行组合好的模板关键词列表,关键词顺序可以自由搭配(例如[3,5,4]或[4,5,3]),最多支持10个关键词组合
* @param restTemplate 必填
* @return
*/
public static String addTemplate(String access_token, String id, List<Integer> keyword_id_list, RestTemplate restTemplate) { restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8)); // 防止中文乱码
String url = "https://api.weixin.qq.com/cgi-bin/wxopen/template/add?access_token="+access_token;
//请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
//请求体
Map<String, Object> requestParam = new HashMap<>();
requestParam.put("id", id);
requestParam.put("keyword_id_list",keyword_id_list); //封装成一个请求对象
HttpEntity entity = new HttpEntity(requestParam, headers);
//发送数据方法
ResponseEntity<String> forEntity = restTemplate.postForEntity(url, entity, String.class); //得到返回的数据body
return forEntity.getBody();
}
2、
3.返回顶部
 
4.返回顶部
1、
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
// package org.springframework.web.client; import java.io.IOException;
import java.lang.reflect.Type;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.http.ResponseEntity.BodyBuilder;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.support.InterceptingHttpAccessor;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.GenericHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.ResourceHttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.cbor.MappingJackson2CborHttpMessageConverter;
import org.springframework.http.converter.feed.AtomFeedHttpMessageConverter;
import org.springframework.http.converter.feed.RssChannelHttpMessageConverter;
import org.springframework.http.converter.json.GsonHttpMessageConverter;
import org.springframework.http.converter.json.JsonbHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.smile.MappingJackson2SmileHttpMessageConverter;
import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter;
import org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter;
import org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter;
import org.springframework.http.converter.xml.SourceHttpMessageConverter;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.web.util.AbstractUriTemplateHandler;
import org.springframework.web.util.DefaultUriBuilderFactory;
import org.springframework.web.util.UriTemplateHandler;
import org.springframework.web.util.DefaultUriBuilderFactory.EncodingMode; public class RestTemplate extends InterceptingHttpAccessor implements RestOperations {
private static boolean romePresent;
private static final boolean jaxb2Present;
private static final boolean jackson2Present;
private static final boolean jackson2XmlPresent;
private static final boolean jackson2SmilePresent;
private static final boolean jackson2CborPresent;
private static final boolean gsonPresent;
private static final boolean jsonbPresent;
private final List<HttpMessageConverter<?>> messageConverters;
private ResponseErrorHandler errorHandler;
private UriTemplateHandler uriTemplateHandler;
private final ResponseExtractor<HttpHeaders> headersExtractor; public RestTemplate() {
this.messageConverters = new ArrayList();
this.errorHandler = new DefaultResponseErrorHandler();
this.headersExtractor = new RestTemplate.HeadersExtractor();
this.messageConverters.add(new ByteArrayHttpMessageConverter());
this.messageConverters.add(new StringHttpMessageConverter());
this.messageConverters.add(new ResourceHttpMessageConverter(false)); try {
this.messageConverters.add(new SourceHttpMessageConverter());
} catch (Error var2) {
;
} 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());
} if (jackson2Present) {
this.messageConverters.add(new MappingJackson2HttpMessageConverter());
} else if (gsonPresent) {
this.messageConverters.add(new GsonHttpMessageConverter());
} else if (jsonbPresent) {
this.messageConverters.add(new JsonbHttpMessageConverter());
} if (jackson2SmilePresent) {
this.messageConverters.add(new MappingJackson2SmileHttpMessageConverter());
} if (jackson2CborPresent) {
this.messageConverters.add(new MappingJackson2CborHttpMessageConverter());
} this.uriTemplateHandler = initUriTemplateHandler();
} public RestTemplate(ClientHttpRequestFactory requestFactory) {
this();
this.setRequestFactory(requestFactory);
} public RestTemplate(List<HttpMessageConverter<?>> messageConverters) {
this.messageConverters = new ArrayList();
this.errorHandler = new DefaultResponseErrorHandler();
this.headersExtractor = new RestTemplate.HeadersExtractor();
Assert.notEmpty(messageConverters, "At least one HttpMessageConverter required");
this.messageConverters.addAll(messageConverters);
this.uriTemplateHandler = initUriTemplateHandler();
} private static DefaultUriBuilderFactory initUriTemplateHandler() {
DefaultUriBuilderFactory uriFactory = new DefaultUriBuilderFactory();
uriFactory.setEncodingMode(EncodingMode.URI_COMPONENT);
return uriFactory;
} public void setMessageConverters(List<HttpMessageConverter<?>> messageConverters) {
Assert.notEmpty(messageConverters, "At least one HttpMessageConverter required");
if (this.messageConverters != messageConverters) {
this.messageConverters.clear();
this.messageConverters.addAll(messageConverters);
} } public List<HttpMessageConverter<?>> getMessageConverters() {
return this.messageConverters;
} public void setErrorHandler(ResponseErrorHandler errorHandler) {
Assert.notNull(errorHandler, "ResponseErrorHandler must not be null");
this.errorHandler = errorHandler;
} public ResponseErrorHandler getErrorHandler() {
return this.errorHandler;
} public void setDefaultUriVariables(Map<String, ?> uriVars) {
if (this.uriTemplateHandler instanceof DefaultUriBuilderFactory) {
((DefaultUriBuilderFactory)this.uriTemplateHandler).setDefaultUriVariables(uriVars);
} else {
if (!(this.uriTemplateHandler instanceof AbstractUriTemplateHandler)) {
throw new IllegalArgumentException("This property is not supported with the configured UriTemplateHandler.");
} ((AbstractUriTemplateHandler)this.uriTemplateHandler).setDefaultUriVariables(uriVars);
} } public void setUriTemplateHandler(UriTemplateHandler handler) {
Assert.notNull(handler, "UriTemplateHandler must not be null");
this.uriTemplateHandler = handler;
} public UriTemplateHandler getUriTemplateHandler() {
return this.uriTemplateHandler;
} @Nullable
public <T> T getForObject(String url, Class<T> responseType, Object... uriVariables) throws RestClientException {
RequestCallback requestCallback = this.acceptHeaderRequestCallback(responseType);
HttpMessageConverterExtractor<T> responseExtractor = new HttpMessageConverterExtractor(responseType, this.getMessageConverters(), this.logger);
return this.execute(url, HttpMethod.GET, requestCallback, responseExtractor, (Object[])uriVariables);
} @Nullable
public <T> T getForObject(String url, Class<T> responseType, Map<String, ?> uriVariables) throws RestClientException {
RequestCallback requestCallback = this.acceptHeaderRequestCallback(responseType);
HttpMessageConverterExtractor<T> responseExtractor = new HttpMessageConverterExtractor(responseType, this.getMessageConverters(), this.logger);
return this.execute(url, HttpMethod.GET, requestCallback, responseExtractor, (Map)uriVariables);
} @Nullable
public <T> T getForObject(URI url, Class<T> responseType) throws RestClientException {
RequestCallback requestCallback = this.acceptHeaderRequestCallback(responseType);
HttpMessageConverterExtractor<T> responseExtractor = new HttpMessageConverterExtractor(responseType, this.getMessageConverters(), this.logger);
return this.execute(url, HttpMethod.GET, requestCallback, responseExtractor);
} public <T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Object... uriVariables) throws RestClientException {
RequestCallback requestCallback = this.acceptHeaderRequestCallback(responseType);
ResponseExtractor<ResponseEntity<T>> responseExtractor = this.responseEntityExtractor(responseType);
return (ResponseEntity)nonNull(this.execute(url, HttpMethod.GET, requestCallback, responseExtractor, uriVariables));
} public <T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Map<String, ?> uriVariables) throws RestClientException {
RequestCallback requestCallback = this.acceptHeaderRequestCallback(responseType);
ResponseExtractor<ResponseEntity<T>> responseExtractor = this.responseEntityExtractor(responseType);
return (ResponseEntity)nonNull(this.execute(url, HttpMethod.GET, requestCallback, responseExtractor, uriVariables));
} public <T> ResponseEntity<T> getForEntity(URI url, Class<T> responseType) throws RestClientException {
RequestCallback requestCallback = this.acceptHeaderRequestCallback(responseType);
ResponseExtractor<ResponseEntity<T>> responseExtractor = this.responseEntityExtractor(responseType);
return (ResponseEntity)nonNull(this.execute(url, HttpMethod.GET, requestCallback, responseExtractor));
} public HttpHeaders headForHeaders(String url, Object... uriVariables) throws RestClientException {
return (HttpHeaders)nonNull(this.execute(url, HttpMethod.HEAD, (RequestCallback)null, this.headersExtractor(), (Object[])uriVariables));
} public HttpHeaders headForHeaders(String url, Map<String, ?> uriVariables) throws RestClientException {
return (HttpHeaders)nonNull(this.execute(url, HttpMethod.HEAD, (RequestCallback)null, this.headersExtractor(), (Map)uriVariables));
} public HttpHeaders headForHeaders(URI url) throws RestClientException {
return (HttpHeaders)nonNull(this.execute(url, HttpMethod.HEAD, (RequestCallback)null, this.headersExtractor()));
} @Nullable
public URI postForLocation(String url, @Nullable Object request, Object... uriVariables) throws RestClientException {
RequestCallback requestCallback = this.httpEntityCallback(request);
HttpHeaders headers = (HttpHeaders)this.execute(url, HttpMethod.POST, requestCallback, this.headersExtractor(), uriVariables);
return headers != null ? headers.getLocation() : null;
} @Nullable
public URI postForLocation(String url, @Nullable Object request, Map<String, ?> uriVariables) throws RestClientException {
RequestCallback requestCallback = this.httpEntityCallback(request);
HttpHeaders headers = (HttpHeaders)this.execute(url, HttpMethod.POST, requestCallback, this.headersExtractor(), uriVariables);
return headers != null ? headers.getLocation() : null;
} @Nullable
public URI postForLocation(URI url, @Nullable Object request) throws RestClientException {
RequestCallback requestCallback = this.httpEntityCallback(request);
HttpHeaders headers = (HttpHeaders)this.execute(url, HttpMethod.POST, requestCallback, this.headersExtractor());
return headers != null ? headers.getLocation() : null;
} @Nullable
public <T> T postForObject(String url, @Nullable Object request, Class<T> responseType, Object... uriVariables) throws RestClientException {
RequestCallback requestCallback = this.httpEntityCallback(request, responseType);
HttpMessageConverterExtractor<T> responseExtractor = new HttpMessageConverterExtractor(responseType, this.getMessageConverters(), this.logger);
return this.execute(url, HttpMethod.POST, requestCallback, responseExtractor, (Object[])uriVariables);
} @Nullable
public <T> T postForObject(String url, @Nullable Object request, Class<T> responseType, Map<String, ?> uriVariables) throws RestClientException {
RequestCallback requestCallback = this.httpEntityCallback(request, responseType);
HttpMessageConverterExtractor<T> responseExtractor = new HttpMessageConverterExtractor(responseType, this.getMessageConverters(), this.logger);
return this.execute(url, HttpMethod.POST, requestCallback, responseExtractor, (Map)uriVariables);
} @Nullable
public <T> T postForObject(URI url, @Nullable Object request, Class<T> responseType) throws RestClientException {
RequestCallback requestCallback = this.httpEntityCallback(request, responseType);
HttpMessageConverterExtractor<T> responseExtractor = new HttpMessageConverterExtractor(responseType, this.getMessageConverters());
return this.execute(url, HttpMethod.POST, requestCallback, responseExtractor);
} public <T> ResponseEntity<T> postForEntity(String url, @Nullable Object request, Class<T> responseType, Object... uriVariables) 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, uriVariables));
} public <T> ResponseEntity<T> postForEntity(String url, @Nullable Object request, Class<T> responseType, Map<String, ?> uriVariables) 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, uriVariables));
} 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));
} public void put(String url, @Nullable Object request, Object... uriVariables) throws RestClientException {
RequestCallback requestCallback = this.httpEntityCallback(request);
this.execute(url, HttpMethod.PUT, requestCallback, (ResponseExtractor)null, (Object[])uriVariables);
} public void put(String url, @Nullable Object request, Map<String, ?> uriVariables) throws RestClientException {
RequestCallback requestCallback = this.httpEntityCallback(request);
this.execute(url, HttpMethod.PUT, requestCallback, (ResponseExtractor)null, (Map)uriVariables);
} public void put(URI url, @Nullable Object request) throws RestClientException {
RequestCallback requestCallback = this.httpEntityCallback(request);
this.execute(url, HttpMethod.PUT, requestCallback, (ResponseExtractor)null);
} @Nullable
public <T> T patchForObject(String url, @Nullable Object request, Class<T> responseType, Object... uriVariables) throws RestClientException {
RequestCallback requestCallback = this.httpEntityCallback(request, responseType);
HttpMessageConverterExtractor<T> responseExtractor = new HttpMessageConverterExtractor(responseType, this.getMessageConverters(), this.logger);
return this.execute(url, HttpMethod.PATCH, requestCallback, responseExtractor, (Object[])uriVariables);
} @Nullable
public <T> T patchForObject(String url, @Nullable Object request, Class<T> responseType, Map<String, ?> uriVariables) throws RestClientException {
RequestCallback requestCallback = this.httpEntityCallback(request, responseType);
HttpMessageConverterExtractor<T> responseExtractor = new HttpMessageConverterExtractor(responseType, this.getMessageConverters(), this.logger);
return this.execute(url, HttpMethod.PATCH, requestCallback, responseExtractor, (Map)uriVariables);
} @Nullable
public <T> T patchForObject(URI url, @Nullable Object request, Class<T> responseType) throws RestClientException {
RequestCallback requestCallback = this.httpEntityCallback(request, responseType);
HttpMessageConverterExtractor<T> responseExtractor = new HttpMessageConverterExtractor(responseType, this.getMessageConverters());
return this.execute(url, HttpMethod.PATCH, requestCallback, responseExtractor);
} public void delete(String url, Object... uriVariables) throws RestClientException {
this.execute(url, HttpMethod.DELETE, (RequestCallback)null, (ResponseExtractor)null, (Object[])uriVariables);
} public void delete(String url, Map<String, ?> uriVariables) throws RestClientException {
this.execute(url, HttpMethod.DELETE, (RequestCallback)null, (ResponseExtractor)null, (Map)uriVariables);
} public void delete(URI url) throws RestClientException {
this.execute(url, HttpMethod.DELETE, (RequestCallback)null, (ResponseExtractor)null);
} public Set<HttpMethod> optionsForAllow(String url, Object... uriVariables) throws RestClientException {
ResponseExtractor<HttpHeaders> headersExtractor = this.headersExtractor();
HttpHeaders headers = (HttpHeaders)this.execute(url, HttpMethod.OPTIONS, (RequestCallback)null, headersExtractor, (Object[])uriVariables);
return headers != null ? headers.getAllow() : Collections.emptySet();
} public Set<HttpMethod> optionsForAllow(String url, Map<String, ?> uriVariables) throws RestClientException {
ResponseExtractor<HttpHeaders> headersExtractor = this.headersExtractor();
HttpHeaders headers = (HttpHeaders)this.execute(url, HttpMethod.OPTIONS, (RequestCallback)null, headersExtractor, (Map)uriVariables);
return headers != null ? headers.getAllow() : Collections.emptySet();
} public Set<HttpMethod> optionsForAllow(URI url) throws RestClientException {
ResponseExtractor<HttpHeaders> headersExtractor = this.headersExtractor();
HttpHeaders headers = (HttpHeaders)this.execute(url, HttpMethod.OPTIONS, (RequestCallback)null, headersExtractor);
return headers != null ? headers.getAllow() : Collections.emptySet();
} public <T> ResponseEntity<T> exchange(String url, HttpMethod method, @Nullable HttpEntity<?> requestEntity, Class<T> responseType, Object... uriVariables) throws RestClientException {
RequestCallback requestCallback = this.httpEntityCallback(requestEntity, responseType);
ResponseExtractor<ResponseEntity<T>> responseExtractor = this.responseEntityExtractor(responseType);
return (ResponseEntity)nonNull(this.execute(url, method, requestCallback, responseExtractor, uriVariables));
} public <T> ResponseEntity<T> exchange(String url, HttpMethod method, @Nullable HttpEntity<?> requestEntity, Class<T> responseType, Map<String, ?> uriVariables) throws RestClientException {
RequestCallback requestCallback = this.httpEntityCallback(requestEntity, responseType);
ResponseExtractor<ResponseEntity<T>> responseExtractor = this.responseEntityExtractor(responseType);
return (ResponseEntity)nonNull(this.execute(url, method, requestCallback, responseExtractor, uriVariables));
} public <T> ResponseEntity<T> exchange(URI url, HttpMethod method, @Nullable HttpEntity<?> requestEntity, Class<T> responseType) throws RestClientException {
RequestCallback requestCallback = this.httpEntityCallback(requestEntity, responseType);
ResponseExtractor<ResponseEntity<T>> responseExtractor = this.responseEntityExtractor(responseType);
return (ResponseEntity)nonNull(this.execute(url, method, requestCallback, responseExtractor));
} public <T> ResponseEntity<T> exchange(String url, HttpMethod method, @Nullable HttpEntity<?> requestEntity, ParameterizedTypeReference<T> responseType, Object... uriVariables) throws RestClientException {
Type type = responseType.getType();
RequestCallback requestCallback = this.httpEntityCallback(requestEntity, type);
ResponseExtractor<ResponseEntity<T>> responseExtractor = this.responseEntityExtractor(type);
return (ResponseEntity)nonNull(this.execute(url, method, requestCallback, responseExtractor, uriVariables));
} public <T> ResponseEntity<T> exchange(String url, HttpMethod method, @Nullable HttpEntity<?> requestEntity, ParameterizedTypeReference<T> responseType, Map<String, ?> uriVariables) throws RestClientException {
Type type = responseType.getType();
RequestCallback requestCallback = this.httpEntityCallback(requestEntity, type);
ResponseExtractor<ResponseEntity<T>> responseExtractor = this.responseEntityExtractor(type);
return (ResponseEntity)nonNull(this.execute(url, method, requestCallback, responseExtractor, uriVariables));
} public <T> ResponseEntity<T> exchange(URI url, HttpMethod method, @Nullable HttpEntity<?> requestEntity, ParameterizedTypeReference<T> responseType) throws RestClientException {
Type type = responseType.getType();
RequestCallback requestCallback = this.httpEntityCallback(requestEntity, type);
ResponseExtractor<ResponseEntity<T>> responseExtractor = this.responseEntityExtractor(type);
return (ResponseEntity)nonNull(this.execute(url, method, requestCallback, responseExtractor));
} public <T> ResponseEntity<T> exchange(RequestEntity<?> requestEntity, Class<T> responseType) throws RestClientException {
RequestCallback requestCallback = this.httpEntityCallback(requestEntity, responseType);
ResponseExtractor<ResponseEntity<T>> responseExtractor = this.responseEntityExtractor(responseType);
return (ResponseEntity)nonNull(this.doExecute(requestEntity.getUrl(), requestEntity.getMethod(), requestCallback, responseExtractor));
} public <T> ResponseEntity<T> exchange(RequestEntity<?> requestEntity, ParameterizedTypeReference<T> responseType) throws RestClientException {
Type type = responseType.getType();
RequestCallback requestCallback = this.httpEntityCallback(requestEntity, type);
ResponseExtractor<ResponseEntity<T>> responseExtractor = this.responseEntityExtractor(type);
return (ResponseEntity)nonNull(this.doExecute(requestEntity.getUrl(), requestEntity.getMethod(), requestCallback, responseExtractor));
} @Nullable
public <T> T execute(String url, HttpMethod method, @Nullable RequestCallback requestCallback, @Nullable ResponseExtractor<T> responseExtractor, Object... uriVariables) throws RestClientException {
URI expanded = this.getUriTemplateHandler().expand(url, uriVariables);
return this.doExecute(expanded, method, requestCallback, responseExtractor);
} @Nullable
public <T> T execute(String url, HttpMethod method, @Nullable RequestCallback requestCallback, @Nullable ResponseExtractor<T> responseExtractor, Map<String, ?> uriVariables) throws RestClientException {
URI expanded = this.getUriTemplateHandler().expand(url, uriVariables);
return this.doExecute(expanded, method, requestCallback, responseExtractor);
} @Nullable
public <T> T execute(URI url, HttpMethod method, @Nullable RequestCallback requestCallback, @Nullable ResponseExtractor<T> responseExtractor) throws RestClientException {
return this.doExecute(url, method, requestCallback, responseExtractor);
} @Nullable
protected <T> T doExecute(URI url, @Nullable HttpMethod method, @Nullable RequestCallback requestCallback, @Nullable ResponseExtractor<T> responseExtractor) throws RestClientException {
Assert.notNull(url, "URI is required");
Assert.notNull(method, "HttpMethod is required");
ClientHttpResponse response = null; Object var14;
try {
ClientHttpRequest request = this.createRequest(url, method);
if (requestCallback != null) {
requestCallback.doWithRequest(request);
} response = request.execute();
this.handleResponse(url, method, response);
var14 = responseExtractor != null ? responseExtractor.extractData(response) : null;
} catch (IOException var12) {
String resource = url.toString();
String query = url.getRawQuery();
resource = query != null ? resource.substring(0, resource.indexOf(63)) : resource;
throw new ResourceAccessException("I/O error on " + method.name() + " request for \"" + resource + "\": " + var12.getMessage(), var12);
} finally {
if (response != null) {
response.close();
} } return var14;
} protected void handleResponse(URI url, HttpMethod method, ClientHttpResponse response) throws IOException {
ResponseErrorHandler errorHandler = this.getErrorHandler();
boolean hasError = errorHandler.hasError(response);
if (this.logger.isDebugEnabled()) {
try {
int code = response.getRawStatusCode();
HttpStatus status = HttpStatus.resolve(code);
this.logger.debug("Response " + (status != null ? status : code));
} catch (IOException var8) {
;
}
} if (hasError) {
errorHandler.handleError(url, method, response);
} } public <T> RequestCallback acceptHeaderRequestCallback(Class<T> responseType) {
return new RestTemplate.AcceptHeaderRequestCallback(responseType);
} public <T> RequestCallback httpEntityCallback(@Nullable Object requestBody) {
return new RestTemplate.HttpEntityRequestCallback(requestBody);
} public <T> RequestCallback httpEntityCallback(@Nullable Object requestBody, Type responseType) {
return new RestTemplate.HttpEntityRequestCallback(requestBody, responseType);
} public <T> ResponseExtractor<ResponseEntity<T>> responseEntityExtractor(Type responseType) {
return new RestTemplate.ResponseEntityResponseExtractor(responseType);
} protected ResponseExtractor<HttpHeaders> headersExtractor() {
return this.headersExtractor;
} private static <T> T nonNull(@Nullable T result) {
Assert.state(result != null, "No result");
return result;
} static {
ClassLoader classLoader = RestTemplate.class.getClassLoader();
romePresent = ClassUtils.isPresent("com.rometools.rome.feed.WireFeed", classLoader);
jaxb2Present = ClassUtils.isPresent("javax.xml.bind.Binder", classLoader);
jackson2Present = ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", classLoader) && ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", classLoader);
jackson2XmlPresent = ClassUtils.isPresent("com.fasterxml.jackson.dataformat.xml.XmlMapper", classLoader);
jackson2SmilePresent = ClassUtils.isPresent("com.fasterxml.jackson.dataformat.smile.SmileFactory", classLoader);
jackson2CborPresent = ClassUtils.isPresent("com.fasterxml.jackson.dataformat.cbor.CBORFactory", classLoader);
gsonPresent = ClassUtils.isPresent("com.google.gson.Gson", classLoader);
jsonbPresent = ClassUtils.isPresent("javax.json.bind.Jsonb", classLoader);
} private static class HeadersExtractor implements ResponseExtractor<HttpHeaders> {
private HeadersExtractor() {
} public HttpHeaders extractData(ClientHttpResponse response) {
return response.getHeaders();
}
} private class ResponseEntityResponseExtractor<T> implements ResponseExtractor<ResponseEntity<T>> {
@Nullable
private final HttpMessageConverterExtractor<T> delegate; public ResponseEntityResponseExtractor(@Nullable Type responseType) {
if (responseType != null && Void.class != responseType) {
this.delegate = new HttpMessageConverterExtractor(responseType, RestTemplate.this.getMessageConverters(), RestTemplate.this.logger);
} else {
this.delegate = null;
} } public ResponseEntity<T> extractData(ClientHttpResponse response) throws IOException {
if (this.delegate != null) {
T body = this.delegate.extractData(response);
return ((BodyBuilder)ResponseEntity.status(response.getRawStatusCode()).headers(response.getHeaders())).body(body);
} else {
return ((BodyBuilder)ResponseEntity.status(response.getRawStatusCode()).headers(response.getHeaders())).build();
}
}
} private class HttpEntityRequestCallback extends RestTemplate.AcceptHeaderRequestCallback {
private final HttpEntity<?> requestEntity; public HttpEntityRequestCallback(@Nullable Object requestBody) {
this(requestBody, (Type)null);
} public HttpEntityRequestCallback(@Nullable Object requestBody, @Nullable Type responseType) {
super(responseType);
if (requestBody instanceof HttpEntity) {
this.requestEntity = (HttpEntity)requestBody;
} else if (requestBody != null) {
this.requestEntity = new HttpEntity(requestBody);
} else {
this.requestEntity = HttpEntity.EMPTY;
} } public void doWithRequest(ClientHttpRequest httpRequest) throws IOException {
super.doWithRequest(httpRequest);
Object requestBody = this.requestEntity.getBody();
if (requestBody == null) {
HttpHeaders httpHeaders = httpRequest.getHeaders();
HttpHeaders requestHeaders = this.requestEntity.getHeaders();
if (!requestHeaders.isEmpty()) {
requestHeaders.forEach((key, values) -> {
httpHeaders.put(key, new LinkedList(values));
});
} if (httpHeaders.getContentLength() < 0L) {
httpHeaders.setContentLength(0L);
} } else {
Class<?> requestBodyClass = requestBody.getClass();
Type requestBodyType = this.requestEntity instanceof RequestEntity ? ((RequestEntity)this.requestEntity).getType() : requestBodyClass;
HttpHeaders httpHeadersx = httpRequest.getHeaders();
HttpHeaders requestHeadersx = this.requestEntity.getHeaders();
MediaType requestContentType = requestHeadersx.getContentType();
Iterator var8 = RestTemplate.this.getMessageConverters().iterator(); while(var8.hasNext()) {
HttpMessageConverter<?> messageConverter = (HttpMessageConverter)var8.next();
if (messageConverter instanceof GenericHttpMessageConverter) {
GenericHttpMessageConverter<Object> genericConverter = (GenericHttpMessageConverter)messageConverter;
if (genericConverter.canWrite((Type)requestBodyType, requestBodyClass, requestContentType)) {
if (!requestHeadersx.isEmpty()) {
requestHeadersx.forEach((key, values) -> {
httpHeadersx.put(key, new LinkedList(values));
});
} this.logBody(requestBody, requestContentType, genericConverter);
genericConverter.write(requestBody, (Type)requestBodyType, requestContentType, httpRequest);
return;
}
} else if (messageConverter.canWrite(requestBodyClass, requestContentType)) {
if (!requestHeadersx.isEmpty()) {
requestHeadersx.forEach((key, values) -> {
httpHeadersx.put(key, new LinkedList(values));
});
} this.logBody(requestBody, requestContentType, messageConverter);
messageConverter.write(requestBody, requestContentType, httpRequest);
return;
}
} String message = "No HttpMessageConverter for " + requestBodyClass.getName();
if (requestContentType != null) {
message = message + " and content type \"" + requestContentType + "\"";
} throw new RestClientException(message);
}
} private void logBody(Object body, @Nullable MediaType mediaType, HttpMessageConverter<?> converter) {
if (RestTemplate.this.logger.isDebugEnabled()) {
if (mediaType != null) {
RestTemplate.this.logger.debug("Writing [" + body + "] as \"" + mediaType + "\"");
} else {
RestTemplate.this.logger.debug("Writing [" + body + "] with " + converter.getClass().getName());
}
} }
} private class AcceptHeaderRequestCallback implements RequestCallback {
@Nullable
private final Type responseType; public AcceptHeaderRequestCallback(@Nullable Type responseType) {
this.responseType = responseType;
} public void doWithRequest(ClientHttpRequest request) throws IOException {
if (this.responseType != null) {
List<MediaType> allSupportedMediaTypes = (List)RestTemplate.this.getMessageConverters().stream().filter((converter) -> {
return this.canReadResponse(this.responseType, converter);
}).flatMap(this::getSupportedMediaTypes).distinct().sorted(MediaType.SPECIFICITY_COMPARATOR).collect(Collectors.toList());
if (RestTemplate.this.logger.isDebugEnabled()) {
RestTemplate.this.logger.debug("Accept=" + allSupportedMediaTypes);
} request.getHeaders().setAccept(allSupportedMediaTypes);
} } private boolean canReadResponse(Type responseType, HttpMessageConverter<?> converter) {
Class<?> responseClass = responseType instanceof Class ? (Class)responseType : null;
if (responseClass != null) {
return converter.canRead(responseClass, (MediaType)null);
} else if (converter instanceof GenericHttpMessageConverter) {
GenericHttpMessageConverter<?> genericConverter = (GenericHttpMessageConverter)converter;
return genericConverter.canRead(responseType, (Class)null, (MediaType)null);
} else {
return false;
}
} private Stream<MediaType> getSupportedMediaTypes(HttpMessageConverter<?> messageConverter) {
return messageConverter.getSupportedMediaTypes().stream().map((mediaType) -> {
return mediaType.getCharset() != null ? new MediaType(mediaType.getType(), mediaType.getSubtype()) : mediaType;
});
}
}
}
2、
5.返回顶部
1、
2、
 
6.返回顶部
 
作者:ylbtech
出处:http://ylbtech.cnblogs.com/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

Java-Class-C:org.springframework.web.client.RestTemplate的更多相关文章

  1. Spring Cloud ZooKeeper集成Feign的坑1,错误:Consider defining a bean of type 'org.springframework.web.client.RestTemplate' in your configuration.

    错误如下: ERROR 31473 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** A ...

  2. Consider defining a bean of type 'org.springframework.web.client.RestTemplate' in your configuration

    https://www.cnblogs.com/EasonJim/p/7546136.html 错误如下: ERROR 31473 --- [ main] o.s.b.d.LoggingFailure ...

  3. org.springframework.web.client.HttpClientErrorException: 400 null

    异常代码: org.springframework.web.client.HttpClientErrorException: 400 null 已解决. 百度了一下400代表无法解析请求. 说明请求是 ...

  4. SSM报错:No converter found for return value of type: class java.util.ArrayList at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverter

    我使用的是SSM框架,是在编写测试RESTFUL接口的时候出现, @RequestMapping(value = "/selectAll", method = RequestMet ...

  5. Java-Class-I:org.springframework.web.mutipart.MutipartFile

    ylbtech-Java-Class-I:org.springframework.web.mutipart.MutipartFile 1.返回顶部   2.返回顶部 1.1. import org.s ...

  6. Spring MVC报异常:org.springframework.web.util.NestedServletException: Request processing failed

    在使用SpringMVC绑定基本类型(如String,Integer等)参数时,应通过@RequestParam注解指定具体的参数名称,否则,当源代码在非debug模式下编译后,运行时会引发Handl ...

  7. 项目maven update 后启动项目出现导常:org.springframework.web.context.ContextLoaderListener

    导常:org.springframework.web.context.ContextLoaderListener 1. 右键单击工程项目 ->点击 properties2. 选择 Deploym ...

  8. Java-API-Package:org.springframework.web.bind.annotation

    ylbtech-Java-API-Package:org.springframework.web.bind.annotation 1.返回顶部 1. @NonNullApi @NonNullField ...

  9. Java-Class-@I:org.springframework.web.bind.annotation.PostMapping

    ylbtech-Java-Class-@I:org.springframework.web.bind.annotation.PostMapping 1.返回顶部   2.返回顶部 1. package ...

随机推荐

  1. Tool ALL Framework

    //https://www.cnblogs.com/jiftle/p/10895260.html C++ 资源大全 关于 C++ 框架.库和资源的一些汇总列表,内容包括:标准库.Web应用框架.人工智 ...

  2. vue基础三

    1.模板语法 在底层的实现上, Vue 将模板编译成虚拟 DOM 渲染函数.如果你熟悉虚拟 DOM 并且偏爱 JavaScript 的原始力量,你也可以不用模板,直接写渲染(render)函数,使用可 ...

  3. SCP-bzoj-1054

    项目编号:bzoj-1054 项目等级:Safe 项目描述: 戳这里 特殊收容措施: 直接状压BFS即可,我实现的比较渣..复杂度O(45*216). 附录: #include <bits/st ...

  4. 剑指offer---1、顺时针打印矩阵

    剑指offer---1.顺时针打印矩阵 一.总结 一句话总结: 谋而后动+多做:还是要谋而后动,但是怎么谋而后动,很有学问,做好的方式就是多做 问题就这些问题:解决了就好了,比如php多维数组 面试的 ...

  5. Shell基本正则表达式和扩展正则表达式

    BRE和ERE的区别 基本正则表达式(BRE)和扩展正则表达式(ERE)的区别仅仅是元字符(meta charactor)的区别而已. BRE: 只有^$.*[]是元字符 ERE: ^$.[]*+() ...

  6. Zabbix 历史数据存储到 Elasticsearch

    Zabbix 历史数据存储到 Elasticsearch Zabbix 3.4.6 版本开始支持历史数据存储到 Elasticsearch, 早就想测试这个功能,最近有个需求需保存 zabbix 的历 ...

  7. 如何解决Unsupported major.minor version 52.0问题?

    为什么出现Unsupported major.minor version 52.0? You get this error because a Java 7 VM tries to load a cl ...

  8. 【React-Native】---Android环境配置

    一.前言 本文主要内容是在Window系统下配置Android APP的开发环境,要配置RN的Android开发环境需要3个依赖 1.JDK(版本必须是 1.8) 2.Node(版本必须高于8.3) ...

  9. error C4996: 'getcwd': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _getcwd. See online help for details. c:\users\12968\desktop\testapp\testapp\testapp.c

    解决办法: 属性>C/C++>预处理器定义>分别输入: _CRT_SECURE_NO_WARNINGS _CRT_SECURE_NO_DEPRECATE >保存退出即可

  10. 关于Ms Sql server 表列等是否存在

    select object_id('名称') ,object_id('名称','类型') 1. 等价于 select * from sys.objects where name ='名称' selec ...