RestTemplate.exchange()不编码'+'?

问题描述 投票:0回答:1

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

java spring spring-boot url encode
1个回答
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"))然后将编码的param传递给RestTemplate,说明URI已经使用builder.build(true).toUri();编码,其中true告诉RestTemplate URI是alrady编码的,所以不再编码,因此+将被传递为%2B

  1. 使用qazxsw poi OUTPUT:qazxsw poi作为编码将执行一次。
  2. 使用qazxsw poi OUTPUT:qazxsw poi作为编码将执行两次。
© www.soinside.com 2019 - 2024. All rights reserved.