URL encoding using the new Spring UriComponentsBuilder

后端 未结 3 685
清歌不尽
清歌不尽 2020-11-30 08:31

I\'m attempting to use spring\'s UriComponentsBuilder to generate some urls for oauth interaction. The query parameters include such entities as callback urls and parameter

相关标签:
3条回答
  • 2020-11-30 09:09

    from what I understand, UriComponentsBuilder doesn't encode the query parameters automatically, just the original HttpUrl it's instantiated with. In other words, you still have to explicitly encode:

    String redirectURI= "https://oauth2-login-demo.appspot.com/code";
    urlBuilder.queryParam("redirect_uri", URLEncoder.encode(redirectURI,"UTF-8" ));
    
    0 讨论(0)
  • 2020-11-30 09:11

    UriComponentsBuilder is encoding your URI in accordance with RFC 3986, with section 3.4 about the 'query' component of a URI being of particular note.

    Within the 'query' component, the characters '/' and ':' are permitted, and do not need escaping.

    To take the '/' character for example: the 'query' component (which is clearly delimited by unescaped '?' and (optionally) '#' characters), is not hierarchical and the '/' character has no special meaning. So it doesn't need encoding.

    0 讨论(0)
  • 2020-11-30 09:14

    Try to scan the UriComponentsBuilder doc, there is method named build(boolean encoded)

    Sample code 1:

    UriComponents uriComponents = UriComponentsBuilder.fromPath("/path1/path2").build(true);
    

    Here is my sample code 2:

    UriComponents uriComponents = UriComponentsBuilder.newInstance()
                .scheme("https")
                .host("my.host")
                .path("/path1/path2").query(parameters).build(true);
    
    URI uri= uriComponents.toUri();
    
    ResponseEntity<MyEntityResponse> responseEntity = restTemplate.exchange(uri,
                HttpMethod.GET, entity, typeRef);
    
    0 讨论(0)
提交回复
热议问题