如果与ClientHttpRequestInterceptor一起使用,Spring Resttemplate postforobject返回null作为对象响应 [英] Spring Resttemplate postforobject returns null as object response if used with ClientHttpRequestInterceptor

查看:584
本文介绍了如果与ClientHttpRequestInterceptor一起使用,Spring Resttemplate postforobject返回null作为对象响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Rest服务,并且正在使用Spring RestTemplate postForObjectMethod发布一些数据,但是即使我可以在有效负载中看到请求和响应,也得到了空响应.

[更新]我正在使用拦截器实现ClientHttpRequestInterceptor,如果我将其删除,则会得到响应.

[PS:该服务配置为POST,出于显而易见的原因,理想情况下应为GET,但我仍然很好奇为什么没有响应作为发布的一部分出现,即使我在http日志中也能看到相同的消息.]

基于Spring MVC 4的配置应用程序

应用上下文:

 <bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
        <property name="messageConverters">
            <list>
                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
            </list>
        </property>
        <property name="interceptors">
            <list>
                <bean class="com.sipl.interceptors.LoggingRequestInterceptor" />
            </list>
        </property>
</bean>

Jackson POM

<dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>${jackson.version}</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>${jackson.version}</version>
    </dependency>


    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>${jackson.version}</version>
    </dependency>

拦截器类

public class LoggingRequestInterceptor implements ClientHttpRequestInterceptor {

    final static Logger logger = LoggerFactory.getLogger(LoggingRequestInterceptor.class);

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {

        traceRequest(request, body);
        ClientHttpResponse response = execution.execute(request, body);
        traceResponse(response);
        return response;
    }

    private void traceRequest(HttpRequest request, byte[] body) throws IOException {
        logger.debug("===========================request begin================================================");

        logger.debug("URI : " + request.getURI());
        logger.debug("Method : " + request.getMethod());
        logger.debug("Request Body : " + new String(body, "UTF-8"));
        logger.debug("==========================request end================================================");
    }

    private void traceResponse(ClientHttpResponse response) throws IOException {
        StringBuilder inputStringBuilder = new StringBuilder();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getBody(), "UTF-8"));
        String line = bufferedReader.readLine();
        while (line != null) {
            inputStringBuilder.append(line);
            inputStringBuilder.append('\n');
            line = bufferedReader.readLine();
        }
        logger.debug("============================response begin==========================================");
        logger.debug("status code: " + response.getStatusCode());
        logger.debug("status text: " + response.getStatusText());
        logger.debug("Response Body : " + inputStringBuilder.toString());
        logger.debug("=======================response end=================================================");
    }

}

GetAllEmployeesClass

public class GetAllEmployeesVO {
    private ResponseVO response;
    private List<EmployeeBean> employees;
    private String actionCode;

    public String getActionCode() {
        return actionCode;
    }

    public void setActionCode(String actionCode) {
        this.actionCode = actionCode;
    }

    public ResponseVO getResponse() {
        return response;
    }

    public void setResponse(ResponseVO response) {
        this.response = response;
    }

    public List<EmployeeBean> getEmployees() {
        return employees;
    }

    public void setEmployees(List<EmployeeBean> employees) {
        this.employees = employees;
    }
}

控制器

@RestController
public class RestAdminstrationController {
    @Autowired
    private RestTemplate restTemplate;
    @Value("${rest.getallemployees.api.endpoint}")
    private String getEmpEndpt;

    @RequestMapping(value = AppConstatants.GET_EXISTING_APP_USERS, method = RequestMethod.POST)

    public List<EmployeeBean> loadAppAdminUsers(@RequestBody GetAllEmployeesVO userData) {

        try {
            //get Rest Service Data
            GetAllEmployeesVO resp= restTemplate.postForObject(getEmpEndpt,userData,GetAllEmployeesVO.class);
            //resp is coming as null

请求响应HTTP有效负载日志:

 2015-12-12 15:45:53 DEBUG RestTemplate:79 - Created POST request for "http://103.35.123.23:8080/siplrestservices/sipl/EmployeeService/getAllEmployees"
2015-12-12 15:45:53 DEBUG RestTemplate:720 - Setting request Accept header to [application/json, application/*+json]
2015-12-12 15:45:53 DEBUG RestTemplate:797 - Writing [com.sipl.common.beans.GetAllEmployeesVO@1dd42575] using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@52e7339f]
2015-12-12 15:45:53 DEBUG LoggingRequestInterceptor:36 - ===========================request begin================================================
2015-12-12 15:45:53 DEBUG LoggingRequestInterceptor:38 - URI : http://xxxxx:8080/siplrestservices/sipl/EmployeeService/getAllEmployees
2015-12-12 15:45:53 DEBUG LoggingRequestInterceptor:39 - Method : POST
2015-12-12 15:45:53 DEBUG LoggingRequestInterceptor:40 - Request Body : {"response":null,"employees":null,"actionCode":"M"}
2015-12-12 15:45:53 DEBUG LoggingRequestInterceptor:41 - ==========================request end================================================
2015-12-12 15:45:54 DEBUG LoggingRequestInterceptor:53 - ============================response begin==========================================
2015-12-12 15:45:54 DEBUG LoggingRequestInterceptor:54 - status code: 201
2015-12-12 15:45:54 DEBUG LoggingRequestInterceptor:55 - status text: Created
2015-12-12 15:45:54 DEBUG LoggingRequestInterceptor:56 - **Response Body : {"employees":[{"commonName":"MOHAN KUMAR GHOSHAL","countryCode":"","dateOfJoining":"2015-11-23","designationId":"4","division":"GENERAL","emailId":"","employeeId":"1","employeeNo":"M-392","employeeStatus":"1","hqCityId":"2","lastWorkingDate":"2015-11-23","mobile":{"mobileStatus":"1"},"mobileNo":"1234567890"}],"response":{"respCd":"0","respDesc":"SUCCESS"}}**

2015-12-12 15:45:54 DEBUG LoggingRequestInterceptor:57 - =======================response end=================================================
2015-12-12 15:45:54 DEBUG RestTemplate:632 - POST request for "http://xxxxx:8080/siplrestservices/sipl/EmployeeService/getAllEmployees" resulted in 201 (Created)
 

解决方案

您可以使用BufferingClientHttpRequestFactory. 它允许多次读取响应.

I am trying to consume a rest service and i am posting some data, with Spring RestTemplate postForObjectMethod but i am getting a null response, even though i can see the request and response in payload.

[Update] I am using an interceptor implmenting ClientHttpRequestInterceptor, if i remove it, i am getting the response.

[PS: the service is configured as POST, ideally it should be GET for obvious reason, but i am still curious why no response is coming as part of post, even i can see the same in http logs.]

Configuration Spring MVC 4 based application

Application context:

 <bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
        <property name="messageConverters">
            <list>
                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
            </list>
        </property>
        <property name="interceptors">
            <list>
                <bean class="com.sipl.interceptors.LoggingRequestInterceptor" />
            </list>
        </property>
</bean>

Jackson POM

<dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>${jackson.version}</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>${jackson.version}</version>
    </dependency>


    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>${jackson.version}</version>
    </dependency>

Interceptor Class

public class LoggingRequestInterceptor implements ClientHttpRequestInterceptor {

    final static Logger logger = LoggerFactory.getLogger(LoggingRequestInterceptor.class);

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {

        traceRequest(request, body);
        ClientHttpResponse response = execution.execute(request, body);
        traceResponse(response);
        return response;
    }

    private void traceRequest(HttpRequest request, byte[] body) throws IOException {
        logger.debug("===========================request begin================================================");

        logger.debug("URI : " + request.getURI());
        logger.debug("Method : " + request.getMethod());
        logger.debug("Request Body : " + new String(body, "UTF-8"));
        logger.debug("==========================request end================================================");
    }

    private void traceResponse(ClientHttpResponse response) throws IOException {
        StringBuilder inputStringBuilder = new StringBuilder();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getBody(), "UTF-8"));
        String line = bufferedReader.readLine();
        while (line != null) {
            inputStringBuilder.append(line);
            inputStringBuilder.append('\n');
            line = bufferedReader.readLine();
        }
        logger.debug("============================response begin==========================================");
        logger.debug("status code: " + response.getStatusCode());
        logger.debug("status text: " + response.getStatusText());
        logger.debug("Response Body : " + inputStringBuilder.toString());
        logger.debug("=======================response end=================================================");
    }

}

GetAllEmployeesClass

public class GetAllEmployeesVO {
    private ResponseVO response;
    private List<EmployeeBean> employees;
    private String actionCode;

    public String getActionCode() {
        return actionCode;
    }

    public void setActionCode(String actionCode) {
        this.actionCode = actionCode;
    }

    public ResponseVO getResponse() {
        return response;
    }

    public void setResponse(ResponseVO response) {
        this.response = response;
    }

    public List<EmployeeBean> getEmployees() {
        return employees;
    }

    public void setEmployees(List<EmployeeBean> employees) {
        this.employees = employees;
    }
}

Controller

@RestController
public class RestAdminstrationController {
    @Autowired
    private RestTemplate restTemplate;
    @Value("${rest.getallemployees.api.endpoint}")
    private String getEmpEndpt;

    @RequestMapping(value = AppConstatants.GET_EXISTING_APP_USERS, method = RequestMethod.POST)

    public List<EmployeeBean> loadAppAdminUsers(@RequestBody GetAllEmployeesVO userData) {

        try {
            //get Rest Service Data
            GetAllEmployeesVO resp= restTemplate.postForObject(getEmpEndpt,userData,GetAllEmployeesVO.class);
            //resp is coming as null

Request Response HTTP payload logs:

2015-12-12 15:45:53 DEBUG RestTemplate:79 - Created POST request for "http://103.35.123.23:8080/siplrestservices/sipl/EmployeeService/getAllEmployees"
2015-12-12 15:45:53 DEBUG RestTemplate:720 - Setting request Accept header to [application/json, application/*+json]
2015-12-12 15:45:53 DEBUG RestTemplate:797 - Writing [com.sipl.common.beans.GetAllEmployeesVO@1dd42575] using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@52e7339f]
2015-12-12 15:45:53 DEBUG LoggingRequestInterceptor:36 - ===========================request begin================================================
2015-12-12 15:45:53 DEBUG LoggingRequestInterceptor:38 - URI : http://xxxxx:8080/siplrestservices/sipl/EmployeeService/getAllEmployees
2015-12-12 15:45:53 DEBUG LoggingRequestInterceptor:39 - Method : POST
2015-12-12 15:45:53 DEBUG LoggingRequestInterceptor:40 - Request Body : {"response":null,"employees":null,"actionCode":"M"}
2015-12-12 15:45:53 DEBUG LoggingRequestInterceptor:41 - ==========================request end================================================
2015-12-12 15:45:54 DEBUG LoggingRequestInterceptor:53 - ============================response begin==========================================
2015-12-12 15:45:54 DEBUG LoggingRequestInterceptor:54 - status code: 201
2015-12-12 15:45:54 DEBUG LoggingRequestInterceptor:55 - status text: Created
2015-12-12 15:45:54 DEBUG LoggingRequestInterceptor:56 - **Response Body : {"employees":[{"commonName":"MOHAN KUMAR GHOSHAL","countryCode":"","dateOfJoining":"2015-11-23","designationId":"4","division":"GENERAL","emailId":"","employeeId":"1","employeeNo":"M-392","employeeStatus":"1","hqCityId":"2","lastWorkingDate":"2015-11-23","mobile":{"mobileStatus":"1"},"mobileNo":"1234567890"}],"response":{"respCd":"0","respDesc":"SUCCESS"}}**

2015-12-12 15:45:54 DEBUG LoggingRequestInterceptor:57 - =======================response end=================================================
2015-12-12 15:45:54 DEBUG RestTemplate:632 - POST request for "http://xxxxx:8080/siplrestservices/sipl/EmployeeService/getAllEmployees" resulted in 201 (Created)

解决方案

You can use BufferingClientHttpRequestFactory. It allows multiple reading of the response.

这篇关于如果与ClientHttpRequestInterceptor一起使用,Spring Resttemplate postforobject返回null作为对象响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆