栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

import java.io.UnsupportedEncodingException;import java.net.URI;import java.net.URLEnprer;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", URLEnprer.enpre("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(
URLEnprer.enpre("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,因为编码将进行两次。


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/395455.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号