简体   繁体   中英

How to URL-encode the the whole xml value of a query param using Spring's rest template?

I am working on a Spring Boot application

I need to make a request to an external service, old and ill-conceived. The request take the form of a HTTP GET (or POST) call, but the payload, an xml content, need to be passed as a query parameter. For example,

GET http://ill-service.com/plain.cgi?XML_DATA=<request attribute="attributeValue"><content contentAttribute="plain"/></request>

Of course, the value of query param XML_DATA need to be URL encoded, and normally, the RestTemplate of Spring boot work good on that, following RFC 3986 (see http://www.ietf.org/rfc/rfc3986.txt ).

Except that, as allowed by this RFC, '/' and '=' character are left in the param value, giving me the following query :

GET http://ill-service.com/plain.cgi?XML_DATA=%3Crequest%20attribute=%22attributeValue%22%3E%3Ccontent%20contentAttribute=%22plain%22/%3E%3C/request%3E

In a perfect wold, this would be good, but do you remember when I said that the service I am trying to call is ill-conceived ? In another world, it needs to have the full content of XML_DATA URL-encoded. In another words, it needs the following query:

GET http://ill-service.com/plain.cgi?XML_DATA=%3Crequest%20attribute%3D%22attributeValue%22%3E%3Ccontent%20contentAttribute%3D%22plain%22%2F%3E%3C%2Frequest%3E%0A

I am quite lost on how to instruct the rest template or the UriComponentBuilder I am using to do so. Any help would be greatly appreciated

也许你可以使用spring的UriUtils

首先使用java.net.URLEncoderXML有效负载进行编码,然后附加编码后的有效负载。

Following the suggestion of Vasif, and some information about UriComponentBuilder I found the following solutions :

String xmlContent = "<request attribute="attributeValue"><content contentAttribute="plain"/></request>";

URI uri = UriComponentsBuilder.fromHttpUrl("http://ill-service.com/plain.cgi")
    //This part set the query param as a full encoded value, not as query value encoded
    .queryParam("XML_DATA", UriUtils.encode(xmlContent, "UTF-8"))
    //The build(true) indicate to the builder that the Uri is already encoded
    .build(true).toUri();

String responseStr = restTemplate.getForObject(uri ,String.class)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM