Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to solve the problem that the percent sign in the RestTemplate request url will be escaped to 25

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Editor to share with you how to solve the problem that the percent sign in the RestTemplate request url will be escaped into 25, I believe most people do not know much about it, so share this article for your reference. I hope you will get a lot after reading this article. Let's learn about it together.

The percent sign contained in the RestTemplate request url will be escaped to 25

The initial method for remote invocation using RestTemplate is as follows:

Private String getRemoteData (String url) {logger.info ("Request URL:" + url + "|"); String resp = rest.getForObject (url, String.class); logger.info ("Response result:" + resp.toString ()); return resp;}

However, it is found that the result of the request has been empty.

Finally, it is found that in our business scenario, the request parameter contains the Chinese requirement to transcode according to the specified rules, resulting in the request url containing%, and RestTemplate will automatically call the encode method to escape, escaping the% to% 25.

Solution method

Self-built URI input:

Private String getRemoteData (String url) {logger.info ("Request URL:" + url + "|"); String resp = null; try {URI uri = new URI (url); resp = rest.getForObject (uri, String.class);} catch (URISyntaxException e) {logger.error ("Create URI Exception!");} logger.info ("Response result:" + resp.toString ()); return resp;} RestTemplate transcoding bug

Found a rare bug for Get requests for HTTP.

Background of transcoding problem

You need to send a complex get request to the tigergraph server with only one parameter, but the value of the parameter is a complex json

The value received by the server is always abnormal. It is observed that the anomaly is that the place where the server is supposed to be resolved to a space has become a plus sign (+).

Think that there is something wrong with the code, and then use the native way of HTTPclient to initiate the request:

Public static String doGet (String url) throws Exception {HttpGet get = new HttpGet (url); return doMethod (get);} private static String doMethod (HttpRequestBase method) throws Exception {CloseableHttpResponse response = null; CloseableHttpClient client; HttpClientBuilder hcb = HttpClientBuilder.create (); HttpRequestRetryHandler hrrh = new DefaultHttpRequestRetryHandler (); HttpClientBuilder httpClientBuilder = hcb.setRetryHandler (hrrh); client = httpClientBuilder.build () Method.addHeader ("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1 SV1)"); method.addHeader (HTTP.CONTENT_TYPE, APPLICATION_JSON); RequestConfig.Builder confBuilder = RequestConfig.custom (); confBuilder.setConnectTimeout (CONNECT_TIMEOUT); confBuilder.setConnectionRequestTimeout (REQUEST_TIMEOUT); confBuilder.setSocketTimeout (SOCKET_TIMEOUT); RequestConfig config = confBuilder.build () Method.setConfig (config); response = client.execute (method); int code = response.getStatusLine (). GetStatusCode (); String result = EntityUtils.toString (response.getEntity ()); response.close (); client.close (); return result;}

Getting results is the same problem, as is building http requests using Assured test tools.

Conclusion

Later, after carefully examining the URLEncode.encode method and the RestTemplate source code implementation, it is found that the mismatch between the client-side transcoding protocol and the server-side decoding protocol is caused.

After repeated testing and serious, this problem only occurs when there is a space in the parameter, and there are no other characters, such as special characters such as / * &.

The final solution is to replace the% 20 space in the transcoded string of the URL string, and then use the native request method of http client.

The second solution is to use the UriComponentsBuilder class of RestTemplate, using (builder.build (false). ToUri () to get URL. The parameter must be false to convert the space to% 20.

/ * urlencode transcoding can not be used casually, because she will convert spaces to the + sign instead of the standard% 20 characters. * this problem does not occur on the server side built by spring. But I encountered this problem on the tiger server. * so urlencode is only applicable to the protocol supported by the server is RFC1738 * if the server only supports the RFC 2396 standard, then the server will decode the plus sign as a reserved character without transcoding * * / @ Override @ SuppressWarnings ("all") public Resp doGet (String url, Req request, Class responseType) throws Exception {UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl (url); Map parameters = (Map) request For (Map.Entry entry: parameters.entrySet ()) {builder.queryParam (entry.getKey (), Objects.toString (entry.getValue (), "));} return restTemplate.getForObject (builder.build (false). ToUri (), responseType);} Why is there such a problem?

The root cause is that the URLEncode class of the Java language can only be applied to the early RFC protocol, and the server side of spring development is usually compatible with this pattern.

The new version of the RFC protocol will no longer reverse the + sign as a keyword into a space, which is usually reflected in new technologies, such as the current tigergraph graph database.

The above is all the contents of this article entitled "how to solve the problem that the percent sign in the RestTemplate request url will be escaped to 25". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report