这是我的应用程序日志中的完整错误消息
Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Illegal character ((CTRL-CHAR, code 31)): only regular white space (\r, \n, \t) is allowed between tokens; nested exception is com.fasterxml.jackson.core.JsonParseException: Illegal character ((CTRL -CHAR, code 31)): only regular white space (\r, \n, \t) is allowed between tokens
我正在使用postman向我的web应用发送post请求,其标题如下:输入是一个gzip,其中包含json。在postman上,它返回400个错误请求
Content-Type: application/json
Content-Encoding: gzip
这是我的发帖方法。我有一个自定义的gzip拦截器类。
@RequestMapping(
method = RequestMethod.POST,
value = "/post"
)
public WekaPredictResp prediction(HttpServletRequest request, HttpServletResponse response, @RequestBody CustomRequest gzipInputs) throws Exception {
postMethod(gzipInputs);
}
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.HttpEntity;
import org.springframework.web.client.RestTemplate;
public static CustomResponse postMethod(CustomRequest gzipInputs) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Map<String, Object>> entity = new HttpEntity<>(gzipInputs.getInputs(), headers);
RestTemplate gzipRestTemplate = new RestTemplateBuilder()
.requestFactory(HttpComponentsClientHttpRequestFactory.class)
.additionalInterceptors(new GzipInterceptor())
.build();
ResponseEntity<Map> responseEntity = gzipRestTemplate.postForEntity(externalUrl, entity, Map.class);
Map<String, Object> outputs = (Map<String, Object>) responseEntity.getBody();
CustomResponse response = new CustomResponse();
response.setOutputs(outputs);
return outputs;
}
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;
public class GzipHttpRequestInterceptor implements ClientHttpRequestInterceptor {
@Override
public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
HttpHeaders httpHeaders = httpRequest.getHeaders();
httpHeaders.add(HttpHeaders.CONTENT_ENCODING, "gzip");
httpHeaders.add(HttpHeaders.ACCEPT_ENCODING, "gzip");
httpHeaders.set(HttpHeaders.CONTENT_TYPE, "gzip"); // Override for compatibility
return clientHttpRequestExecution.execute(httpRequest, compress(bytes));
}
}
1条答案
按热度按时间xqk2d5yq1#
通过包含一个过滤器来跟踪gzip输入并解压缩它,可以在这里找到示例解决方案