Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve XML using webClient in Spring?

I've been trying to retrieve XML using webClient in Spring, but is has not worked out.
I've been getting this error message.

UnsupportedMediaTypeException: Content type 'application/xml;charset=UTF-8' not supported for bodyType

I think the request was ok, but I failed to get the response as an object. I got '200 ok' from the server.
And I tried to send a request with 'Talend API Tester' to see if I made a right one, I got perfect response.

And I had added '@XmlRootElement', '@XmlAttribute's to my DTO.
But, I only had gotten an empty List '[]'.

What should I do to solve this problem?

Here are my codes.

//Service
public List<SearchResponseDto> search(SearchRequestDto searchRequestDto) {

        System.out.println(requestUrl);

        var uri = UriComponentsBuilder.fromUriString(requestUrl)
                .queryParams(searchRequestDto.toMultiValueMap())
                .build()
                .encode()
                .toUri();

        return WebClient.create()
                .get()
                .uri(uri)
                .accept(MediaType.APPLICATION_XML)
                .headers(head -> {
                    head.set("X-Naver-Client-Id", naverId);
                    head.set("X-Naver-Client-Secret", naverSecret);
                })
                .retrieve()
                .bodyToFlux(SearchResponseDto.class)
                .toStream()
                .collect(Collectors.toList());
    }

//responseDTO
@Data
@NoArgsConstructor
@AllArgsConstructor
public class SearchResponseDto {

    private String lastBuildDate;
    private int total;
    private int start;
    private int display;
    private List<SearchItem> item;

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class SearchItem {

        private String title;
        private String link;
        private String image;
        private String author;
        private int price;
        private int discount;
        private String publisher;
        private String isbn;
        private String description;
        private String pubdate;
    }
}
like image 784
broaden-horizon Avatar asked Jul 19 '26 20:07

broaden-horizon


1 Answers

You need to configure additional codec to deserialize Xml response

WebClient.builder()
        .exchangeStrategies(
                ExchangeStrategies.builder()
                        .codecs(configurer -> 
                                configurer.defaultCodecs().jaxb2Decoder(new Jaxb2XmlDecoder())
                        )
                        .build()
        )
        .build();
like image 160
Alex Avatar answered Jul 23 '26 00:07

Alex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!