eight
2024-11-28 d1708b4b2bc6596f9c62354274f1af97be45401c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package cn.lihu.jh.module.ecg.config;
 
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import feign.RequestTemplate;
import feign.Response;
import feign.codec.DecodeException;
import feign.codec.Decoder;
import feign.codec.EncodeException;
import feign.codec.Encoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.IOException;
import java.io.StringWriter;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
 
@Slf4j
public class FeignXmlConfiguration {
 
    @Bean
    public Encoder feignEncoder() {
        return new Encoder.Default() {
            @Override
            public void encode(Object object, Type bodyType, RequestTemplate template) throws EncodeException {
                try {
                    XmlMapper xmlMapper = new XmlMapper();
                    String xml = xmlMapper.writeValueAsString(object);
                    template.body(xml.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8);
                } catch (JsonProcessingException e) {
                    throw new EncodeException(e.getMessage(), e);
                }
            }
        };
    }
 
    @Bean
    public Decoder feignDecoder() {
        return new Decoder.Default() {
            @Override
            public Object decode(Response response, Type type) throws IOException {
                try {
                    XmlMapper xmlMapper = new XmlMapper();
                    return xmlMapper.readValue(response.body().asInputStream(), xmlMapper.constructType(type));
                } catch (IllegalArgumentException e) {
                    throw new DecodeException(response.status(), e.getMessage(), response.request());
                }
            }
        };
    }
}