SpringBoot中使用RestTemplate封装请求头

RestTemplate的基本使用

关于RestTemplate的使用可以参考这篇文章
转载:https://blog.csdn.net/jinjiniao1/article/details/100849237

在RestTemplate中设置请求头和请求体

废话不多说,先上代码

String url = "**********************";
HttpHeaders headers = new HttpHeaders();
//设置content-type
headers.setContentType(MediaType.APPLICATION_JSON);
//设置自定义的session
String session = "*********************";
headers.set("X-CAF-Runtime-Context",session);
//设置cookies,此处的cookies传参传过来的类型是List
//cookies的格式为"name=value",例如"caf_websession=wexcsdfrregcrgrergrgre"
headers.put(HttpHeaders.COOKIE, cookies);
//设置请求体
JSONObject jsonObject = new JSONObject();
jsonObject.put("dataInfo",resultDto.toJSONString());
HttpEntity<String> entity = new HttpEntity<>(jsonObject.toJSONString(),headers);
RestTemplate restTemplate = new RestTemplate();
restTemplate.put(url,entity);

原理剖析

以postForEntity请求为例

RestTemplate中postForEntity方法有三种
在这里插入图片描述
查看其源码

public <T> ResponseEntity<T> postForEntity(String url, @Nullable Object request,
			Class<T> responseType, Object... uriVariables) throws RestClientException {

		RequestCallback requestCallback = httpEntityCallback(request, responseType);
		ResponseExtractor<ResponseEntity<T>> responseExtractor = responseEntityExtractor(responseType);
		return nonNull(execute(url, HttpMethod.POST, requestCallback, responseExtractor, uriVariables));
	}

我们可以注意到它对request的处理是下面这一行代码

RequestCallback requestCallback = httpEntityCallback(request, responseType);

点进去这个方法可以看到它又new了一个HttpEntityRequestCallback

public <T> RequestCallback httpEntityCallback(@Nullable Object requestBody, Type responseType) {
		return new HttpEntityRequestCallback(requestBody, responseType);
	}

这样我们去查看这个HttpEntityRequestCallback(requestBody, responseType)的构造函数

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;
			}
		}

对我们所传递的request到此就比较清晰了,通过代码不难发现我们的请i去最终都会封装成HttpEntity类的对象。那么这个HttpEntity类又是个什么东西呢,我们继续点进去看一下会发现它含有三个属性如下图所示
在这里插入图片描述
这就已经很明显了,HttpEntity类可以设置我们的请求头和请求体,关于请求体的设置就不说了,上面转载的博客里面说的很明显了。我们可以使用HttpHeaders类来设置我们的请求头,这个类定义了很多类似于Authorization、Content-Type这些请求头的常量,如下所示

/**
	 * The HTTP {@code Accept} header field name.
	 * @see <a href="https://tools.ietf.org/html/rfc7231#section-5.3.2">Section 5.3.2 of RFC 7231</a>
	 */
	public static final String ACCEPT = "Accept";
	/**
	 * The HTTP {@code Accept-Charset} header field name.
	 * @see <a href="https://tools.ietf.org/html/rfc7231#section-5.3.3">Section 5.3.3 of RFC 7231</a>
	 */
	public static final String ACCEPT_CHARSET = "Accept-Charset";
	/**
	 * The HTTP {@code Accept-Encoding} header field name.
	 * @see <a href="https://tools.ietf.org/html/rfc7231#section-5.3.4">Section 5.3.4 of RFC 7231</a>
	 */
	public static final String ACCEPT_ENCODING = "Accept-Encoding";
	/**
	 * The HTTP {@code Accept-Language} header field name.
	 * @see <a href="https://tools.ietf.org/html/rfc7231#section-5.3.5">Section 5.3.5 of RFC 7231</a>
	 */
	public static final String ACCEPT_LANGUAGE = "Accept-Language";
	/**
	 * The HTTP {@code Accept-Ranges} header field name.
	 * @see <a href="https://tools.ietf.org/html/rfc7233#section-2.3">Section 5.3.5 of RFC 7233</a>
	 */
	public static final String ACCEPT_RANGES = "Accept-Ranges";
	/**
	 * The CORS {@code Access-Control-Allow-Credentials} response header field name.
	 * @see <a href="https://www.w3.org/TR/cors/">CORS W3C recommendation</a>
	 */
	public static final String ACCESS_CONTROL_ALLOW_CREDENTIALS = "Access-Control-Allow-Credentials";
	/**
	 * The CORS {@code Access-Control-Allow-Headers} response header field name.
	 * @see <a href="https://www.w3.org/TR/cors/">CORS W3C recommendation</a>
	 */
	public static final String ACCESS_CONTROL_ALLOW_HEADERS = "Access-Control-Allow-Headers";
	/**
	 * The CORS {@code Access-Control-Allow-Methods} response header field name.
	 * @see <a href="https://www.w3.org/TR/cors/">CORS W3C recommendation</a>
	 */
	public static final String ACCESS_CONTROL_ALLOW_METHODS = "Access-Control-Allow-Methods";
	/**
	 * The CORS {@code Access-Control-Allow-Origin} response header field name.
	 * @see <a href="https://www.w3.org/TR/cors/">CORS W3C recommendation</a>
	 */
	public static final String ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin";

我们都可以使用对应的set方法进行设置。除了这些常用的,我们还可以直接使用下面的方法进行设置

public void add(String headerName, @Nullable String headerValue)
public void set(String headerName, @Nullable String headerValue)

这些足以满足我们设置自己的请求头了。


版权声明:本文为g13954103148原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。