web-dev-qa-db-fra.com

Obtenir 400 requêtes incorrectes pour Spring RestTemplate POST

Je souhaite utiliser le service Web Spring Rest à l'aide de la méthode POST. Je n'ai pas accès au fichier POJO du côté du client (site Web), je dois donc utiliser JSON du côté du client et POJO du service Web Ci-dessous mon code:

REST Contrôleur

@RequestMapping(value="/updateAdmin", method=RequestMethod.POST, consumes="application/json", headers="Accept=application/json")
public ResponseEntity<String> updateAdmin(@RequestBody Ss_admin admin) {
    try {
        ss_admin_dao.updateAdmin(admin);
    } catch(Exception ex) {
        ex.printStackTrace();
    }
    return new ResponseEntity<String>(HttpStatus.CREATED);
}

POJO

package model;

import Java.io.Serializable;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;

@JsonIgnoreProperties(ignoreUnknown = true)
public class Ss_admin implements Serializable {
@JsonProperty("a_id")
private long a_id;
@JsonProperty("a_username")
private String a_username;
@JsonProperty("a_password")
private String a_password;

public Ss_admin() {}
public long getA_id() {
    return a_id;
}
public void setA_id(long a_id) {
    this.a_id = a_id;
}
public String getA_username() {
    return a_username;
}
public void setA_username(String a_username) {
    this.a_username = a_username;
}
public String getA_password() {
    return a_password;
}
public void setA_password(String a_password) {
    this.a_password = a_password;
}
}

REST Client

try {
        RestTemplate restTemplate = new RestTemplate();
        List<HttpMessageConverter<?>> list = new ArrayList<HttpMessageConverter<?>>();
        list.add(new MappingJackson2HttpMessageConverter());
        restTemplate.setMessageConverters(list);
        //restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(HttpClientBuilder.create().build()));
        String url = "http://localhost:8181/xyz/updateAdmin";
        JSONArray json = new JSONArray();
        JSONObject obj = new JSONObject();
        obj.put("a_username", "testabcd");
        obj.put("a_id", 1);
        obj.put("a_password", "N/A");
        json.put(obj);
        HttpHeaders headers = new HttpHeaders();
        //headers.setContentType(MediaType.APPLICATION_JSON);
        //headers.setAccept(MediaType.APPLICATION_JSON);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        headers.add("Content-Type", MediaType.APPLICATION_JSON.toString());
        //headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        HttpEntity<String> entity = new HttpEntity<String>(obj.toString(), headers);
        restTemplate.exchange(url, HttpMethod.POST, entity, String.class);

        //restTemplate.postForEntity(url, entity, String.class);
    } catch(Exception ex) {
        ex.printStackTrace();
    }

Comme vous pouvez le voir dans les commentaires, j'ai essayé de nombreuses options sans succès.

Trace de la pile

Aug 04, 2017 6:58:12 PM org.springframework.web.client.RestTemplate handleResponseError
WARNING: POST request for "http://localhost:8181/xyz/updateAdmin" resulted in 400 (Bad Request); invoking error handler
org.springframework.web.client.HttpClientErrorException: 400 Bad Request
at  org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.Java:91)
at org.springframework.web.client.RestTemplate.handleResponseError(RestTemplate.Java:576)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.Java:532)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.Java:489)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.Java:431)
at webcontroller.TestController.update(TestController.Java:77)
at Sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at Sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.Java:62)
at Sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.Java:43)
at Java.lang.reflect.Method.invoke(Method.Java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.Java:214)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.Java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.Java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.Java:748)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.Java:689)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.Java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.Java:945)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.Java:876)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.Java:931)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.Java:822)
at javax.servlet.http.HttpServlet.service(HttpServlet.Java:687)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.Java:807)
at javax.servlet.http.HttpServlet.service(HttpServlet.Java:790)
at org.Apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.Java:292)
at org.Apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.Java:207)
at org.Apache.Tomcat.websocket.server.WsFilter.doFilter(WsFilter.Java:52)
at org.Apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.Java:240)
at org.Apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.Java:207)
at org.Apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.Java:212)
at org.Apache.catalina.core.StandardContextValve.invoke(StandardContextValve.Java:106)
at org.Apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.Java:502)
at org.Apache.catalina.core.StandardHostValve.invoke(StandardHostValve.Java:141)
at org.Apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.Java:79)
at org.Apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.Java:616)
at org.Apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.Java:88)
at org.Apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.Java:528)
at org.Apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.Java:1099)
at org.Apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.Java:670)
at org.Apache.Tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.Java:1520)
at org.Apache.Tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.Java:1476)
at Java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.Java:1142)
at Java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.Java:617)
at org.Apache.Tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.Java:61)
at Java.lang.Thread.run(Thread.Java:745)

EDIT J'avais testé REST service Web http://localhost:8181/xyz/updateAdmin en utilisant Postman, et il s'exécute avec succès, mais ne fonctionne pas avec RestTemplate.

PROBLÈME RESOLU Voir ma réponse ci-dessous.

4
Jignesh M. Khatri

Le problème a été résolu en ajoutant le code suivant dans le fichier de configuration du servlet Dispatcher du client REST:

<bean id="jacksonMessageConverter"
    class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
<bean
    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <list>
            <ref bean="jacksonMessageConverter" />
        </list>
    </property>
</bean>

Le code complet de la servlet de répartition est: web-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<context:component-scan base-package="webcontroller" />
<mvc:annotation-driven />
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name = "prefix" value = "/WEB-INF/jsp/" />
  <property name = "suffix" value = ".jsp" />
</bean>

<bean id="jacksonMessageConverter"
    class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
<bean
    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <list>
            <ref bean="jacksonMessageConverter" />
        </list>
    </property>
</bean>

</beans>

Certains codes de la fonction d’appel REST ont également été supprimés. Les modifications suivantes figurent ci-dessous: REST CLIENT

try {
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://localhost:8181/xyz/updateAdmin";
        JSONArray json = new JSONArray();
        JSONObject obj = new JSONObject();
        obj.put("a_username", "testabcd");
        obj.put("a_id", 1);
        //obj.put("a_password", "N/A");
        json.put(obj);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        headers.add("Content-Type", MediaType.APPLICATION_JSON.toString());
        HttpEntity<String> entity = new HttpEntity<String>(obj.toString(), headers);
        restTemplate.exchange(url, HttpMethod.POST, entity, String.class);


    } catch(Exception ex) {
        ex.printStackTrace();
    }
2
Jignesh M. Khatri

Avez-vous essayé sans '/' en valeur?

@RequestMapping(value="updateAdmin", method=RequestMethod.POST, 
consumes="application/json", headers="Accept=application/json")
public ResponseEntity<String> updateAdmin(@RequestBody Ss_admin admin) 
{
    try {
        ss_admin_dao.updateAdmin(admin);
    } catch(Exception ex) {
    ex.printStackTrace();
    }
    return new ResponseEntity<String>(HttpStatus.CREATED);
}
0
KompiKompi