RestTemplate POST с помощью JSon

Еще раз ищу помощь / руководство от экспертов,

Моя проблема в том, что мне нужно создать динамический веб-сайт, который вызывает перезапускаемый сервер для получения данных, все запросы POST и возвращает объект json. Я думаю об использовании Spring RestTemplate для звонков на сервер. Мой сервер работает нормально, то есть в настоящее время некоторые приложения для Android и Apple подключаются к одним и тем же API и работают нормально. Но когда я пытаюсь использовать RestTemplate для подключения к серверу, это дает некоторые ошибки

org.springframework.web.client.HttpClientErrorException: 400 неверный запрос

это мой сервер,

@Controller
public class ABCController
{

     @RequestMapping(method = RequestMethod.POST, value = "/user/authenticate")
     public @ResponseBody LoginResponse login(@RequestParam("email") String email,@RequestParam("password") String password,@RequestParam("facebookId") String facebookId) {

        LoginRequest request = new LoginRequest(email, password, facebookId);

        UserBusiness userBusiness = UserBusinessImpl.getInstance();

        return userBusiness.login(request);

    }
}

А это мои весенние конфиги сервера,

    <?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"      
       xmlns:mvc="http://www.springframework.org/schema/mvc"
        xmlns:jee="http://www.springframework.org/schema/jee"
       xsi:schemaLocation="http://www.springframework.org/schema/beans                         http://www.springframework.org/schema/beans/spring-beans-3.1.xsd                        http://www.springframework.org/schema/context                           http://www.springframework.org/schema/context/spring-context-3.1.xsd                        http://www.springframework.org/schema/mvc                           http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/jee                          http://www.springframework.org/schema/jee/spring-jee-3.0.xsd">  


    <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />

    <bean id="jsonViewResolver" class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
    <bean id="viewResolver" class="org.springframework.web.servlet.view.BeanNameViewResolver" />


    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="jsonConverter" />
            </list>
        </property>
    </bean>

    <bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
    <property name="supportedMediaTypes" value="application/json" />
    </bean> 


    <bean name="abcController" class="com.abc.def.controller.ABCController" />  

    <mvc:annotation-driven />
</beans>

Вот как я пытаюсь вызвать сервер с помощью RestTemplate,

<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
    <!-- <constructor-arg ref="httpClientFactory"/> -->

    <property name="messageConverters">
        <list>
            <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
               <property name="objectMapper">
                    <ref bean="JacksonObjectMapper" />
               </property>
            </bean>

        </list>
    </property>
</bean>

    <bean id="JacksonObjectMapper" class="org.codehaus.jackson.map.ObjectMapper" />

и вот как я его использую (для тестирования)

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("root-context.xml");
     RestTemplate twitter = applicationContext.getBean("restTemplate", RestTemplate.class);

     MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
    map.add("email", "x1@test.com");
     map.add("password", "abc");
     map.add("facebookId", null);

    HttpEntity<LoginResponse> response= twitter.exchange("https://abc.com/Rest/api/user/authenticate", HttpMethod.POST, map, LoginResponse.class);

мой класс ответа на вход и его подклассы,

  1. LoginResponse

открытый класс LoginResponse extends BaseResponse {
личные данные LoginBase; с геттерами и сеттерами
}

  1. База логинов

открытый класс LoginBase {приватный String token;
частный пользователь

 with getters and setters

}
  1. пользователь

открытый класс пользователя {

  private Integer userId; 
  private String email;   
  private Integer status;     
  private String name;

        with getters and setters
}
  1. наконец BaseResponse

открытый класс BaseResponse {
защищенный String statusCode;

    with getter and setter }

Мои вопросы: 1. Почему я получаю эту ошибку, когда я звоню на сервер

ИНФОРМАЦИЯ: org.springframework.beans.factory.support.DefaultListableBeanFactory - Предварительные экземпляры синглетов в org.springframework.beans.factory.support.DefaultListableBeanFactory@63de8f2d: определение бинов [restTemplate,JacksonO] корень фабричной иерархии ПРЕДУПРЕЖДЕНИЕ: org.springframework.web.client.RestTemplate - POST-запрос для "https://abc.com/Rest/api/user/authenticate" привел к 400 (неверный запрос); Вызов обработчика ошибок Исключение в потоке "main" org.springframework.web.client.HttpClientErrorException: 400 неверный запрос в org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandingrali.r.RestTemplate.handleResponseError(RestTemplate.java:494) в org.springframework.web.client.RestTemplate.doExecute (RestTemplate.java:451)

2. Как я могу сопоставить ответ JSON для Java LoginResponse

1 ответ

Возможно, вам придется добавить тип контента и принять заголовки к вашему запросу.

Отображение ответа на LoginResponse может быть сделано прямо так

LoginResponse lResponse = response.getBody();    

или если вы используете restTemplate.postForObject(), ответ будет в форме LoginResponse

Другие вопросы по тегам