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

时间:2018-08-03 15:41:23

标签: java spring spring-boot url encode

RestTemplate.exchange()将对URL中的所有无效字符进行编码,但不会对+进行编码,因为+是有效的URL字符。但是如何在任何URL的查询参数中传递+

1 个答案:

答案 0 :(得分: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字符。因此,您必须首先对参数(URLEncoder.encode("abc+123=", "UTF-8"))进行编码,然后将编码后的参数传递给RestTemplate,以声明URI已经使用builder.build(true).toUri();进行了编码,其中true告诉RestTemplate URI是格式已编码,因此不再需要再次编码,因此+将作为%2B传递。

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