RestTemplate中form请求方式

RestTemplate中form请求方式_第1张图片
1.restTemplate是为我们提供了一种更简便进行远程调用的方式。
一般来说我们常用的提交参数方式有form和payload方式,下面简单记载一下。

form 方式

		HttpHeaders headers = new HttpHeaders();
		//设置为form方式
		headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
		MultiValueMap map = new LinkedMultiValueMap();
		JSONObject request = new JSONObject();
		request.put("caseNo", caseNo);

		map.add("data", request.toJSONString());
		HttpEntity> requestb = new HttpEntity>(map,
				headers);
		ResponseEntity response = restTemplate.postForEntity(apnMessageUrl, requestb, String.class);

payLoad方式

		HttpHeaders headers = new HttpHeaders();
		//定义请求参数类型,这里用json所以是MediaType.APPLICATION_JSON
		headers.setContentType(MediaType.APPLICATION_JSON);
		//RestTemplate带参传的时候要用HttpEntity对象传递
		Map map = new HashMap();
		map.put("userId", userId);
		HttpEntity> request = new HttpEntity>(map, headers);
		
		ResponseEntity entity = restTemplate.postForEntity(url, request, String.class);


后台大致看了RestTemplate和HttpEntity,发现RestTemplate在执行postForObject方法的时候,会先根据请求参数和responseType构造一个HttpEntityRequestCallback对象。并且为这个对象的requestEntity赋值。所以请求参数一般为HttpEntity。

        private HttpEntityRequestCallback(Object requestBody, Type responseType) {
            super(responseType, null);
            if (requestBody instanceof HttpEntity) {
                this.requestEntity = (HttpEntity)requestBody;
            } else if (requestBody != null) {
                this.requestEntity = new HttpEntity(requestBody);
            } else {
                this.requestEntity = HttpEntity.EMPTY;
            }

        }
private final HttpEntity requestEntity;

而HttpEntity的几个构造器如下,

 protected HttpEntity() {
        this((Object)null, (MultiValueMap)null);
    }

    public HttpEntity(T body) {
        this(body, (MultiValueMap)null);
    }

    public HttpEntity(MultiValueMap headers) {
        this((Object)null, headers);
    }

    public HttpEntity(T body, MultiValueMap headers) {
        this.body = body;
        HttpHeaders tempHeaders = new HttpHeaders();
        if (headers != null) {
            tempHeaders.putAll(headers);
        }

        this.headers = HttpHeaders.readOnlyHttpHeaders(tempHeaders);
    }

RestTemplate中form请求方式_第2张图片

你可能感兴趣的:(SpringBoot)