Запрос RestTemplate GET выдает 400 неверных запросов

Я получаю 400 Bad Request, когда отправляю запрос в Rest Service из тестового примера JUnit. ПФБ мой код. Журнал ошибок находится ближе к концу. Пожалуйста, помогите мне решить проблему. Я не получаю никаких сообщений об ошибках, когда вызываю сервер как restTemplate.getForObject (BASE_URL + "/ remote? ServiceName = simpleService & source = WEB", HelloWorld.class), передавая параметры непосредственно в URL-адресе. Но вот как пройти по карте, вот где возникает проблема.

Мой контроллер:

@Controller
@RequestMapping("/remote")

public class RESTController implements IController{

@RequestMapping(method = RequestMethod.GET, headers = "Accept=application/xml,  application/json")
public @ResponseBody HelloWorld getMessage(@RequestParam("serviceName") String serviceName, @RequestParam("source") String source) throws ApplicationException{
    System.out.println("got the request:");
    serviceLocator serviceLocator = new serviceLocator();
    HelloWorld helloWorld = new HelloWorld();
    helloWorld.setMessage(serviceLocator.getMessage(serviceName));
    return helloWorld;
}

Моя конфигурация:

<context:annotation-config />

<context:component-scan base-package="com" />

<mvc:annotation-driven />

<bean
    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <list>
            <bean class="org.springframework.http.converter.FormHttpMessageConverter" />
            <bean
                class="org.springframework.http.converter.StringHttpMessageConverter" />
            <bean id="jsonViewResolver"
                class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
                <property name="objectMapper" ref="JacksonObjectMapper" />
                <property name="supportedMediaTypes">
                    <list>
                        <bean class="org.springframework.http.MediaType">
                            <constructor-arg value="application" />
                            <constructor-arg value="json" />
                            <constructor-arg
                                value="#{T(java.nio.charset.Charset).forName('UTF-8')}" />
                        </bean>
                    </list>
                </property>
            </bean>

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

Мой тест контроллера:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("applicationContextTest.xml")
public class RESTControllerTest {

private static final String BASE_URL = "http://localhost:8080/SimpleServiceWeb/rest";

@Autowired
private RestTemplate restTemplate;

@Test
public void getMessage() throws Exception { 

    String expected = "Hello Spring!";
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setAccept(Collections
            .singletonList(MediaType.APPLICATION_XML));     

    MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
    map.add("serviceName", "simpleService");
    map.add("source", "WEB");

    ObjectMapper mapper = new ObjectMapper();
    ObjectWriter normalWriter = mapper.writer();
    String jsonString = normalWriter.writeValueAsString(map);;
    HttpEntity<Object> requestEntity = new HttpEntity<Object>(httpHeaders);     

    HelloWorld helloWorld = restTemplate.exchange(BASE_URL + "/remote",
             HttpMethod.GET, requestEntity, HelloWorld.class, map) .getBody();

    assertThat(helloWorld.getMessage(), is(expected));
}

}

Моя тестовая конфигурация:

.simple "/>

<mvc:annotation-driven />

<bean id="springServiceLocator" class="com.servicelocator.simple.SpringServiceLocator">
    <property name="simpleService" ref="simpleService" />
</bean>

<bean id="simpleService" class="com.service.simple.SimpleService" />

<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">

    <property name="messageConverters">
        <list>
            <bean class="org.springframework.http.converter.FormHttpMessageConverter" />
            <bean
                class="org.springframework.http.converter.StringHttpMessageConverter" />
            <bean id="jsonViewResolver"
                class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
                <property name="objectMapper" ref="JacksonObjectMapper" />
                <property name="supportedMediaTypes">
                    <list>
                        <bean class="org.springframework.http.MediaType">
                            <constructor-arg value="application" />
                            <constructor-arg value="json" />
                            <constructor-arg
                                value="#{T(java.nio.charset.Charset).forName('UTF-8')}" />
                        </bean>
                    </list>
                </property>
            </bean>

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

<bean id="httpClient" class="org.apache.commons.httpclient.HttpClient">
    <constructor-arg ref="httpClientParams" />
</bean>

<bean id="httpClientParams" class="org.apache.commons.httpclient.params.HttpClientParams">

    <property name="connectionManagerClass"
        value="org.apache.commons.httpclient.MultiThreadedHttpConnectionManager" />
</bean>

<bean id="httpClientFactory"
    class="org.springframework.http.client.CommonsClientHttpRequestFactory">
    <constructor-arg ref="httpClient" />
</bean>

Ошибка:

Может быть, из-за отсутствия конвертера xml Spring не может должным образом упорядочить ваш запрос и, следовательно, дать 400? Тип носителя поддерживается, хотя, как указано в контроллере, и поэтому вы не получаете 415.


person Vijay    schedule 26.09.2013    source источник


Ответы (1)


  1. В messageConverters настроен только конвертер JSON, и я не вижу никаких конвертеров XML.
  2. В тестовом случае вы устанавливаете тип носителя как application / xml.
  3. Я пробовал этот вариант .. Он не работает ... появляется та же ошибка .. Не могли бы вы поделиться каким-нибудь рабочим примером, чтобы я мог точно настроить свой ...

Ваш контроллер принимает типы application / xml и application / json.

person Praba    schedule 26.09.2013
comment
org.springframework.web.client.HttpClientErrorException: 400 Плохой запрос на org.springframework.web.client.DefaultResponseErrorHandler.handleError (DefaultResponseErrorHandler.java:75) на org.springframeclient.web ) в org.springframework.web.client.RestTemplate.doExecute (RestTemplate.java:443) в org.springframework.web.client.RestTemplate.execute (RestTemplate.java:409) в org.springframework.webTemplate.Rest. exchange (RestTemplate.java:384) в test.com.servicefacade.simple.RESTControllerTest.getMessage (RESTControllerTest.java:85) в sun.reflect.NativeMethodAccessorImpl.invoke0 (собственный метод) в sun.reflect.voccessor UnknownMetplhodAccessor ) в sun.reflect.DelegatingMethodAccessorImpl.invoke (Неизвестный источник) в java.lang.reflect.Method.invoke (Неизвестный источник) в org.junit.runners.model.FrameworkMethod $ 1.runReflectiveCall (FrameworkMethod.java .:45) в junit.inter nal.runners.model.ReflectiveCallable.run (ReflectiveCallable.java:15) по адресу org.junit.runners.model.FrameworkMethod.invokeExplosively (FrameworkMethod.java:42) по адресу org.junit.internal.runvokeuMatements.Internal. InvokeMethod.java:20) на org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate (RunBeforeTestMethodCallbacks.java:74) на org.springframework.test.contextAfterMethodCallbacks.java:74) на org.springframework.test.contextAfterAfterMateCoreManager.junethome.junethome.jpg 82) в org.springframework.test.context.junit4.statements.SpringRepeat.evaluate (SpringRepeat.java:72) на org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild (SpringJUnit4ClassRunner.runChild (SpringJUnnerit4ClassRunner. .runners.BlockJUnit4ClassRunner.runChild (BlockJUnit4ClassRunner.java:47) в org.junit.runners.ParentRunner $ 3.run (ParentRunner.java:231) в org.junit.runners.ParentRunner.ParentRunner.java $ 1.schedule org.junit.runners.ParentRunner.runCh ildren (ParentRunner.java:229) в org.junit.runners.ParentRunner.access $ 000 (ParentRunner.java:50) в org.junit.runners.ParentRunner $ 2. оценить (ParentRunner.java:222) в org.springframework. .context.junit4.statements.RunBeforeTestClassCallbacks.evaluate (RunBeforeTestClassCallbacks.java:61) в org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate (RunAfterTestClassCallbacks.evaluateassner.callbacks. (ParentRunner.java:300) в org.springframework.test.context.junit4. SpringJUnit4ClassRunner.run (SpringJUnit4ClassRunner.java:174) по адресу org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run (JUnit4TestReference.jution:50) по адресу org.ecliprune.jdun. TestExecution.java:38) по адресу org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests (RemoteTestRunner.java:467) по адресу org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.javest.runner.RemoteTestRunner. 683) на org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run (RemoteTestRunner.java:390) на org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main (RemoteTestRunner ).java:197 - person Vijay; 27.09.2013