首页 > 解决方案 > HTTPS 响应状态码能否在 Spring 集成中的其他类中可用

问题描述

我需要在拦截器中从 ClientHttpResponse 接收到 response.statusCode(),应该在我创建的 testSubmitPaymentResponseVO 对象中可用,以便可以相应地进行错误处理。但是我不知道在哪里以及如何将响应传递给我的 POJO testSubmitPaymentResponseVO。

<int:channel id="MytestReqRequestChannel"/>

<int:header-enricher input-channel="MytestReqRequestChannel" output-channel="MytestReqEnrichedRequestChannel">
    <int:header name="x-api-key" value="#{configurationService.configuration.getProperty('myKey')}"/>
    <int:header name="Content-Type" value="application/json;charset=UTF-8" />
</int:header-enricher>


<int:object-to-json-transformer input-channel="MytestReqEnrichedRequestChannel"
                                output-channel="MytestReqJSONRequestChannel"/>

<int-http:outbound-gateway
        url="#{configurationService.configuration.getProperty('myURL')}"
        http-method="POST"
        header-mapper="testPaymentHeaderMapper"
        rest-template="testSubmitPaymentRestTemplate"
        request-channel="MytestReqJSONRequestChannel"
        reply-channel="MytestReqJSONResponseChannel"
        charset="UTF-8"
        expected-response-type="java.lang.String">
</int-http:outbound-gateway>

<int:json-to-object-transformer input-channel="MytestReqJSONResponseChannel"
                                output-channel="MytestReqResponseChannel"
                                type="com.test.testb2bintegrations.models.payment.request.testSubmitPaymentResponseVO"/>

<int:channel id="MytestReqResponseChannel"/>

拦截器代码:

public class TestRequestLoggingInterceptor implements ClientHttpRequestInterceptor
{

@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException
{
    ClientHttpResponse response;
    try
    {
        request.getHeaders().setAcceptCharset(Collections.singletonList(Charsets.UTF_8));
        long startTimeinMillis = new Date().getTime();
        response = execution.execute(request, body);
        logResponse(response);
    }
    catch (Exception e)
    {
        LOGGER.error("Error when trying to fetch the information : " + e.getMessage());
        throw new IOException("Connection was unsuccessful!", e);
    }
    return response;
}

private void logResponse(ClientHttpResponse response) throws IOException
{
       String lineSeparator = System.lineSeparator();
        String responseBody = StreamUtils.copyToString(response.getBody(), Charset.forName("UTF-8"));

        StringBuilder responseLog = new StringBuilder();
        responseLog.append("=======================Response Begin==========================").append(lineSeparator);
        responseLog.append("Status code  : {" + response.getStatusCode() + "}").append(lineSeparator);
        responseLog.append("Status text  : {" + response.getStatusText() + "}").append(lineSeparator);
        responseLog.append("Headers      : {" + response.getHeaders() + "}").append(lineSeparator);
        responseLog.append("Response body: {" + responseBody + "}").append(lineSeparator);
        responseLog.append("======================Response End==============================").append(lineSeparator);
}

标签: javaspringspring-integrationresttemplatespring-resttemplate

解决方案


我在评论中给了你一些说明,以便我回答你的问题:java.lang.IllegalArgumentException: 'json' argument must be an instance of: [class java.lang.String, class [B

我们可能会认为这是重复,但如果我在这里也重复自己的话,这不会伤害我。

处理以下内容时,HTTP 响应状态代码存储在相应的标头<int-http:outbound-gateway>ClientHttpResponse

    else {
        replyBuilder = messageBuilderFactory.withPayload(httpResponse);
    }
    replyBuilder.setHeader(org.springframework.integration.http.HttpHeaders.STATUS_CODE,
            httpResponse.getStatusCode());
    return replyBuilder.copyHeaders(headers);

并且此标头仅在下游可用以供您考虑。

如果你真的很想在你的 . 文件中显示那个状态码testSubmitPaymentResponseVO,那么你可能需要一个设置器。

一种方法是实现一些转换器方法来接受您的testSubmitPaymentResponseVO和那个标头并将其设置到您的 POJO 并从该标头返回它:

testSubmitPaymentResponseVO setStatusCode(testSubmitPaymentResponseVO pojo, @Header(name = HttpHeaders.STATUS_CODE) HttpStatus statusCode) {
   pojo.setStatusCode(statusCode);
   return pojo;
}

另一种方法是使用<enricher>组件:

<int:enricher id="userEnricher"
              input-channel="setStatusCodeChannel"
              output-channel="MytestReqResponseChannel">
    <int:property name="StatusCode" expression="headers[http_statusCode]"/>
</int:enricher>

<int:json-to-object-transformer>应该输出到这个新的setStatusCodeChannel.

请参阅文档:https ://docs.spring.io/spring-integration/docs/current/reference/html/message-transformation.html#payload-enricher


推荐阅读