RestTemplate.exchange()-消息标题值中的非法字符

时间:2018-07-19 14:53:06

标签: java spring spring-boot base64 resttemplate

执行java.lang.IllegalArgumentException: Illegal character(s) in message header value方法时出现restTemplate.exchange()错误。

我猜这是一个巨大的HTTP标头,内部将使用base64编码:

  

似乎SDK使用的是旧的“ sun.misc.BASE64Encoder”,如果编码的字符串太长(> 76个字符),它将打破新的行“ \ n”。

Source

我的代码段会产生错误:

HttpHeaders headers = new HttpHeaders();
headers.set("jwt", jwt); // JSON Web Token with length of over 900 characters
HttpEntity<String> entity = new HttpEntity<>("parameters", headers);
ResponseEntity<String> response = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);

但是如何更改RestTemplate使用的base64编码器?

堆栈跟踪:

java.lang.IllegalArgumentException: Illegal character(s) in message header value: eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJJc3N1ZXIiLCJhdWQiOi...

at sun.net.www.protocol.http.HttpURLConnection.checkMessageHeader(Unknown Source) ~[na:1.8.0_91]
at sun.net.www.protocol.http.HttpURLConnection.isExternalMessageHeaderAllowed(Unknown Source) ~[na:1.8.0_91]
at sun.net.www.protocol.http.HttpURLConnection.addRequestProperty(Unknown Source) ~[na:1.8.0_91]
at sun.net.www.protocol.https.HttpsURLConnectionImpl.addRequestProperty(Unknown Source) ~[na:1.8.0_91]
at org.springframework.http.client.SimpleBufferingClientHttpRequest.addHeaders(SimpleBufferingClientHttpRequest.java:104) ~[spring-web-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.http.client.SimpleBufferingClientHttpRequest.executeInternal(SimpleBufferingClientHttpRequest.java:70) ~[spring-web-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48) ~[spring-web-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:53) ~[spring-web-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:596) ~[spring-web-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:557) ~[spring-web-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:475) ~[spring-web-4.2.6.RELEASE.jar:4.2.6.RELEASE]

编辑:
在将堆栈跟踪添加到我的问题时,我发现了错误:base64编码未添加换行符,而是jwt字符串给我提供了服务...

我想我可以删除我的问题,但是当有人偶然发现相同的错误时,可以这样:检查标头值!

1 个答案:

答案 0 :(得分:0)

您可以这样做

 headers.setAcceptCharset(Arrays.asList(Charset.forName("UTF-8")))  

甚至更好的是

restTemplate.getMessageConverters()
        .add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));

考虑到您要将字符集更改为 UTF-8