解析来自RestTemplate请求的远程响应

时间:2018-07-01 20:08:33

标签: java jaxb resttemplate spring-rest

我想使用此RestTemplate代码进行远程POST请求。我尝试过:

       public static void main(String[] args) {
    String token = "d778dh";
    URI uri = UriComponentsBuilder.fromUriString("http://localhost:8080/bogus_rest_api/v1")
            .pathSegment(token)
            .build()
            .toUri();
    HttpEntity<PaymentTransaction> request = new HttpEntity<>(new PaymentTransaction());

    RestTemplate restClient = new RestTemplate();
    restClient.getInterceptors().add(new BasicAuthorizationInterceptor("petrov", "password2"));
    ResponseEntity<PaymentResponse> response = restClient.exchange(uri, HttpMethod.POST,
            request, PaymentResponse.class);
    PaymentResponse foo = response.getBody();
    System.out.println("!!! Calling Bogus Gateway " + foo.getTransactionId());

}

对象发送:

@XmlRootElement(name = "payment_transaction")
public class PaymentTransaction {
    public enum Response {
        failed_response, successful_response
    }

    @XmlElement(name = "transaction_type")
    public String transactionType;
    @XmlElement(name = "transaction_response")
    public Response transactionResponse;
    @XmlElement(name = "response_code")
    public Integer responseCode;
    @XmlElement(name = "technical_message")
    public String technicalMessage;
    @XmlElement(name = "message")
    ......
}

收到的对象:

@XmlRootElement(name = "payment_response")
public class PaymentResponse {

    @XmlElement(name = "transaction_type")
    public String transactionType;
    @XmlElement(name = "transaction_id")
    public String transactionId;
    @XmlElement(name = "amount")
    public Integer amount;
    @XmlElement(name = "currency")
    public String currency;

但是由于我必须配置正确的对象转换而导致错误?

org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter@4f1bfe23

23:06:20.309 [main] DEBUG org.springframework.web.client.RestTemplate - Created POST request for "http://localhost:8080/bogus_rest_api/v1/d778dh"
23:06:20.534 [main] DEBUG org.springframework.web.client.RestTemplate - Setting request Accept header to [application/xml, text/xml, application/json, application/*+xml, application/*+json]
23:06:20.612 [main] DEBUG org.springframework.web.client.RestTemplate - Writing [org.datalis.plugin.rest.models.PaymentTransaction@747f281] using [org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter@1169afe1]
23:06:20.895 [main] DEBUG org.springframework.web.client.RestTemplate - POST request for "http://localhost:8080/bogus_rest_api/v1/d778dh" resulted in 200 (OK)
23:06:20.896 [main] DEBUG org.springframework.web.client.RestTemplate - Reading [class org.datalis.plugin.rest.models.PaymentResponse] as "application/xml;charset=UTF-8" using [org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter@1169afe1]
!!! Calling Bogus Gateway null

完整日志:https://pastebin.com/WdML1yqH

我总是得到Null作为回应。 你能提出我该如何解决这个问题?

0 个答案:

没有答案