wake-up-neo.net

400 schlechte Anfrage für Spring RestTemplate erhalten POST

Ich möchte den Spring Rest-Webdienst mithilfe der Methode POST verwenden. Ich habe keinen Zugriff auf die POJO-Datei am Client-Ende (Website), daher muss JSON am Client-Ende und POJO am Web-Service verwendet werden. Unten ist mein Code:

REST Controller

@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();
    }

Wie Sie in den Kommentaren sehen können, habe ich viele Optionen ohne Erfolg ausprobiert.

Stapelverfolgung

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 Ich hatte REST web-servicehttp://localhost:8181/xyz/updateAdmin mit Postman getestet und es wird erfolgreich ausgeführt, funktioniert jedoch nicht mit RestTemplate.

Problem gelöst Siehe meine Antwort unten.

4

Das Problem wurde durch das Hinzufügen des folgenden Codes in der Dispatcher-Servlet-Konfigurationsdatei von REST Client behoben:

<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>

Der vollständige Code des Dispatcher-Servlets lautet: 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>

Außerdem wurde einiger Code aus der aufrufenden Funktion REST entfernt. Nachfolgend sind die Änderungen aufgeführt: 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

Hast du es ohne '/' probiert?

@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