小编典典

RestTemplate.exchange()不编码“ +”吗?

spring-boot

RestTemplate.exchange()将编码的URL都无效字符,但不+作为+是有效的URL字符。但是如何+在任何URL的查询参数中传递a


阅读 611

收藏
2020-05-30

共1个答案

小编典典

如果您传递给RestTemplate的URI的编码设置为true,那么它将不会对您传递的URI进行编码。

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.util.Collections;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.BufferingClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

class Scratch {

  public static void main(String[] args) {

    RestTemplate rest = new RestTemplate(
        new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory()));

    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", "application/json");
    headers.add("Accept", "application/json");
    HttpEntity<String> requestEntity = new HttpEntity<>(headers);

    UriComponentsBuilder builder = null;
    try {
      builder = UriComponentsBuilder.fromUriString("http://example.com/endpoint")
          .queryParam("param1", URLEncoder.encode("abc+123=", "UTF-8"));
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }

    URI uri = builder.build(true).toUri();
    ResponseEntity responseEntity = rest.exchange(uri, HttpMethod.GET, requestEntity, String.class);
  }

}

因此,如果您需要在其中传递查询参数,+则RestTemplate不会像对+其他+有效URL字符一样对,但对所有其他无效URL字符进行编码。因此,您必须首先对param(URLEncoder.encode("abc+123=", "UTF-8"))进行编码,然后将编码后的参数传递给RestTemplate,以声明URI已使用进行编码builder.build(true).toUri();,其中,true告诉RestTemplate
URI已被完全编码,因此不再进行编码,因此+将作为传递%2B

  1. 使用builder.build(true).toUri(); OUTPUT: http : //example.com/endpoint? param1=abc%2B123%3D,因为编码将执行一次。
  2. 使用builder.build().toUri(); OUTPUT: http : //example.com/endpoint? param1=abc%252B123%253D,因为编码将进行两次。
2020-05-30