当前位置: 首页 > 知识库问答 >
问题:

Spring boot RestTemplate帖子给出400个错误

艾英范
2023-03-14

我在Eclipse Photon上用Java8编写了一个简单的webService,使用RestTemplate发布(使用postForObject)一个对象(称为patentListWrapper),该对象包装了一个对象列表(称为PatentDetails)。我从Java客户机(称为MainWsClient)发布,然后在服务器端的patentDetails中设置一个值,并在客户机中读取patentListWrapper对象。当服务器端(程序SpringWebServiceHello)使用旧的SpringMVC4技术,并且只有一个jar文件(spring-web5.07.release.jar)跟随这个serverSideExample,即web.xml和rest-servlet.xml文件控制访问点时,它可以正常工作。然后,我使用SpringBoot2.03和Spring5.07JAR和Maven编写了另一个服务器端程序(PndGuidRequestWs),该程序具有identicle@RequestMapping方法,但没有web.xml文件和application.properties文件中定义的访问点:

server.port=8082
server.servlet.path=/
#spring.mvc.servlet.path=/
#server.servlet.contextPath=/

当我使用client-arc调用这个新的服务器程序时,它也能正常工作,但当我使用相同的java客户端和完全相同的请求(显然是接受不同的url)调用它时。我得到一个400错误:

2018-12-18 16:56:53,861 [main] INFO  - Running MainWsClient with name = DS fileType = post3
2018-12-18 16:56:54,101 [main] DEBUG - Created POST request for "http://localhost:8082/guidRequest/xmlList"
2018-12-18 16:56:54,145 [main] DEBUG - Setting request Accept header to [application/xml, text/xml, application/json, application/*+xml, application/*+json]
2018-12-18 16:56:54,152 [main] DEBUG - Writing [com.springservice.client.PatentListWrapper@4ba2ca36] using [org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter@3444d69d]
2018-12-18 16:56:54,384 [main] DEBUG - POST request for "http://localhost:8082/guidRequest/xmlList" resulted in 400 (null); invoking error handler
2018-12-18 16:56:54,387 [main] ERROR - DS1B org.springframework.web.client.HttpClientErrorException: 400 null

非工作的PndGuidRequestWs服务器端有:

@RestController
public class PndController {

@RequestMapping(value = "/guidRequest/xmlList", method = RequestMethod.POST, produces = { "application/xml" } )
public PatentListWrapper guidSearchList(@RequestBody  PatentListWrapper patentListWrapper) {

    for (PatentDetails pd : patentListWrapper.getPatentList())
    {
        pd.setGuid("guidSetOnServer3");
    }

    return patentListWrapper;
  }

}

工作(SpringWebServiceHello)服务器端是相同的,除了:

value = "/service/greeting/xml/post2"

Java客户端具有:

public void runCode(String name , String fileType)
{

 String url;

 if (fileType.equalsIgnoreCase("post2")) {
        url = "http://localhost:8080/SpringWebServiceHello/service/greeting/xml/post2";
        // This method is identicle to postToPndGuidRequestWs() but this method works fine.
        postToSpringWebServiceHello(url);
    }else if (fileType.equalsIgnoreCase("post3")) {
        url = "http://localhost:8082/guidRequest/xmlList";      
        // This method gives 404 error          
        postToPndGuidRequestWs(url);
    }   
}

private void postToPndGuidRequestWs(String url) 
{

    PatentListWrapper patentListWrapper = new PatentListWrapper();
    PatentDetails pd = new PatentDetails("CN","108552082","A","00000000",12345,"guidIn");

    List<PatentDetails> patentList = new ArrayList<PatentDetails>();
    patentList.add(pd);
    patentListWrapper.setPatentList(patentList);

    RestTemplate restTemplate = new RestTemplate();

    /* HttpHeaders headers = new HttpHeaders();
    headers.add("header_name", "header_value");
    headers.setContentType(MediaType.APPLICATION_XML);
    HttpEntity<PatentListWrapper> request = new HttpEntity<PatentListWrapper>(patentListWrapper, headers); */

    /*List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
    Jaxb2RootElementHttpMessageConverter jaxbMessageConverter = new Jaxb2RootElementHttpMessageConverter();
    List<MediaType> mediaTypes = new ArrayList<MediaType>();
    mediaTypes.add(MediaType.APPLICATION_XML);
    jaxbMessageConverter.setSupportedMediaTypes(mediaTypes);
    messageConverters.add(jaxbMessageConverter);
    restTemplate.setMessageConverters(messageConverters);*/

    /* headers = new HttpHeaders();
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_XML));
    HttpEntity<String> entity = new HttpEntity<>("parameters", headers);*/


    try {
        patentListWrapper = restTemplate.postForObject(
                url,
                patentListWrapper,
                PatentListWrapper.class);


        logger.debug("DS1A employee obj returned. guid = " +  patentListWrapper.getPatentList().get(0).getGuid());
    }catch(Exception e) {
        logger.error("DS1B " + e);      
    }   
}
<?xml version="1.0" encoding="UTF-8"?>

http://maven.apache.org/xsd/maven-4.0.0.xsd“>4.0.0

<groupId>com.clarivate</groupId>
<artifactId>pndguidrequestws</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>

<name>pndGuidRequestWs</name>
<description>Guid request webService</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.3.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
    <start-class>com.clarivate.pndguidrequestws.PndGuidRequestWsApplication</start-class>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>com.oracle</groupId>
        <artifactId>ojdbc6</artifactId>
        <version>11.2.0.1.0</version> 
      <!--    <scope>provided</scope> --> <!-- DS insert for unix -->
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.apache.tomcat</groupId>
                <artifactId>tomcat-jdbc</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

    <!-- Implementing XML Representation for Spring Boot Services -->
    <dependency>
      <groupId>com.fasterxml.jackson.dataformat</groupId>
      <artifactId>jackson-dataformat-xml</artifactId>
    </dependency>

    <!-- httpcomponents jars are Required by PndGuidGenerator -->
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpcore</artifactId>
    </dependency>

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
    </dependency>
</dependencies>


<build>
    <finalName>PndGuidRequestWs</finalName>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId> 
            <configuration>
                  <executable>true</executable>
            </configuration> 
        </plugin>
    </plugins>      
</build>
</project>

PatentListWrapper类为:

package com.clarivate.pndguidrequestws.model;

import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class PatentListWrapper {

private List<PatentDetails> patentList;

public PatentListWrapper() {}

public List<PatentDetails> getPatentList() {
    return patentList;
}

public void setPatentList(List<PatentDetails> patentList) {
    this.patentList = patentList;
}   

}

欢迎任何建议。

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class PatentListWrapper2 {

private String name;

public  PatentListWrapper2() {}

public  PatentListWrapper2(String name) {
    this.name = name;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

}
<patentListWrapper2>
   <name>DSDS</name>
</patentListWrapper2>
 2018-12-20 09:17:13,931 [main] INFO  - Running MainWsClient with name = DS fileType = post4
2018-12-20 09:17:14,166 [main] DEBUG - Created POST request for "http://localhost:8082/guidRequest/xmlList2"
2018-12-20 09:17:14,200 [main] DEBUG - Setting request Accept header to [application/xml, text/xml, application/json, application/*+xml, application/*+json]
2018-12-20 09:17:14,206 [main] DEBUG - Writing [com.springservice.client.PatentListWrapper2@517cd4b] using [org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter@6cc7b4de]
2018-12-20 09:17:14,246 [main] DEBUG - POST request for "http://localhost:8082/guidRequest/xmlList2" resulted in 200 (null)
2018-12-20 09:17:14,248 [main] DEBUG - Reading [com.springservice.client.PatentListWrapper2] as "application/xml;charset=UTF-8" using [org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter@6cc7b4de]
2018-12-20 09:17:14,255 [main] ERROR - DS2B org.springframework.web.client.RestClientException: Error while extracting response for type [class com.springservice.client.PatentListWrapper2] and content type [application/xml;charset=UTF-8]; nested exception is org.springframework.http.converter.HttpMessageNotReadableException: Could not unmarshal to [class com.springservice.client.PatentListWrapper2]: unexpected element (uri:"", local:"PatentListWrapper2"). Expected elements are <{}patentListWrapper2>; nested exception is javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"PatentListWrapper2"). Expected elements are <{}patentListWrapper2>

EDIT2我在Eclipse Tomcat上运行了pndGuidRequestWs,而不是-Run As->Spring Boot app。服务器日志如下:

2018-12-20 11:15:45.655  WARN 236 --- [nio-8080-exec-6] .w.s.m.s.DefaultHandlerExceptionResolver : Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of `com.clarivate.pndguidrequestws.model.PatentDetails` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('CN'); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `com.clarivate.pndguidrequestws.model.PatentDetails` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('CN') at [Source: (PushbackInputStream); line: 1, column: 98] (through reference chain: com.clarivate.pndguidrequestws.model.PatentListWrapper["patentList"]->java.util.ArrayList[0])         

共有1个答案

司马同
2023-03-14

您能用以下方法进行测试吗:

try {
        HttpHeaders headers = new HttpHeaders();
        //headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        //headers.setContentType((MediaType.APPLICATION_JSON));
        // I comment the code abouve because you did not specify a consumes whitch  defines the media types that the methods of 
        //a resource class or MessageBodyReader can accept. If not specified, a container will assume that any media type is acceptable.
        HttpEntity<PatentListWrapper> request = new HttpEntity<>(patentListWrapper, headers);
        PatentListWrapper patentListWrapperResult =  = restTemplate.exchange(url, HttpMethod.POST, request,PatentListWrapper.class);


        logger.debug("DS1A employee obj returned. guid = " +  patentListWrapper.getPatentList().get(0).getGuid());
    }catch(Exception e) {
        logger.error("DS1B " + e);      
    } 
 类似资料:
  • 我试图使用Jquery发送一个Ajax POST请求,但我有400个错误请求。 这是我的代码: 它说:无法根据请求构建资源。我错过了什么?

  • 我正在RestTemplate中使用exchange for GET方法。但是在exchange方法中传递requestEntity时,我得到了400个错误的请求。下面是我正在使用的代码。 生成URL: 我尝试从postman访问producer URL,其标题为Content-Type:Application/JSON,正文为{“firstName”:“a”,“lastName”:“b”,“da

  • 当试图将我的JSON映射到Spring MVC控制器中的Java对象时,我在Ajax请求上收到了400个错误请求。我已经检查了主题中的大部分相关问题,但仍然无法使其工作 Ajax调用和JSON: 我的控制器: 我的Java对象: 我使用Spring 4.2.5和Jackson: 我遇到的错误: HTTP错误400访问/ux/词汇表/createVocationary时出现问题。原因:糟糕的请求 此

  • 我正在为一个项目使用Hackerrank API。查看官方文档,点击这里! 在他们的网站上有一个使用UNIREST的例子, 由于我使用的是axios,所以我将其转换为类似的axios代码,如下所示: 我希望这只适用于示例中所示的示例,但它给我带来了以下错误: 请求失败,状态代码为400 错误:请求失败,状态代码为400 在createError(createError.js:16) 在sett(s

  • 我在用Retrofit2。发送一个带有主体的POST请求(作为JSON数组),但得到的是“400 Bad request”。同时,从SoapUI和我的http客户机(基于HttpURLConnection)发送请求也很好。 响应的内容类型是text/plain,但应该是application/json 例如,使用SOAPUI的请求/响应:请求: 及其回应: null 这是服务器endpoint:

  • 问题内容: 我是django-1.6的新手。当我使用运行django服务器时,它运行良好。但是,当我改变DEBUG到False在设置文件,然后在服务器停止,并让在命令提示符下以下错误: 更改为之后,在浏览器中出现错误: 是否可以在没有调试模式的情况下运行Django? 问题答案: 该ALLOWED_HOSTS列表应包含标准主机名,而不是 URL。省略端口和协议。如果你使用127.0.0.1,我也将