[英]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 我正在使用Spring Boot应用程序
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.
该请求采用HTTP GET(或POST)调用的形式,但是有效载荷(即xml内容)需要作为查询参数传递。 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 ). 当然,查询参数XML_DATA的值需要进行URL编码,通常,遵循RFC 3986(请参阅http://www.ietf.org/rfc/rfc3986.txt),Spring boot的RestTemplate可以很好地工作。
Except that, as allowed by this RFC, '/' and '=' character are left in the param value, giving me the following query : 除此之外,在此RFC允许的范围内,在参数值中保留了'/'和'='字符,这给了我以下查询:
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.
在另一个世界中,它需要具有XML_DATA URL编码的完整内容。 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. 我对如何指导其余模板或正在使用的UriComponentBuilder颇为迷惑。 Any help would be greatly appreciated
任何帮助将不胜感激
也许你可以使用spring的UriUtils
类
首先使用java.net.URLEncoder
对XML
有效负载进行编码,然后附加编码后的有效负载。
Following the suggestion of Vasif, and some information about UriComponentBuilder I found the following solutions : 遵循Vasif的建议以及有关UriComponentBuilder的一些信息,我找到了以下解决方案:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.