简体   繁体   中英

How to parse octet-stream as json in Jackson xml parser?

I sometimes receive a webservice response where the content-type=application/octet-stream is set, anyways it's in fact application/xml .

As I'm not in control of the webservice, I'd still like to tell jackson (that I'm using with spring-boot ) to parse those responses as xml. But how?

I first tried to allow octet-stream at all for the jackson mapper, which works so far:

@Bean
public RestTemplateCustomizer customizeJackson2MessageConverter() {
    return restTemplate -> {
        for (var converter : restTemplate.getMessageConverters()) {
            if (converter instanceof MappingJackson2HttpMessageConverter) { 
                jackson.getSupportedMediaTypes().add((MediaType.APPLICATION_OCTET_STREAM);
            }
        }
    };
}

BUT: when it then comes to the parsing, how can I tell jackson to ignore/rewrite the content-type, and still parse it as normal json?

Caused by: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unexpected character ('<' (code 60)): expected a valid value (number, String, array, object, 'true', 'false' or 'null'); nested exception is com.fasterxml.jackson.core.JsonParseException: Unexpected character ('<' (code 60)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
 at [Source: (ByteArrayInputStream); line: 1, column: 2]
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:245) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:227) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:102) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    ... 113 more

I did as advised by @chrylis:

public class ContentTypeInterceptor implements ClientHttpRequestInterceptor {
    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        ClientHttpResponse http = execution.execute(request, body);

        HttpHeaders headers = http.getHeaders();
        if (headers.getContentType() == MediaType.APPLICATION_OCTET_STREAM) {
            headers.setContentType(MediaType.APPLICATION_XML);
        }

        return http;
    }
}

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