java 将 JSON 发布到控制器返回 400 错误请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27687513/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 12:13:46  来源:igfitidea点击:

Posting JSON to Controller returns 400 Bad Request

javaspringrest

提问by Nilam Naik

I am developing RESTful services. I am not able to POST JSON data to controller.

我正在开发 RESTful 服务。我无法将 JSON 数据发布到控制器。

I am using the following dependencies:

我正在使用以下依赖项:

  • Spring : 3.2.3.RELEASE
  • Hymanson : 1.9.6
  • 春天:3.2.3.RELEASE
  • Hyman逊:1.9.6

I also tried:

我也试过:

  • Spring 3.2.3.RELEASE w/ Hymanson 1.9.9
  • Spring 3.1.1.RELEASE w/ Hymanson 1.9.9
  • Spring 3.2.3.RELEASE 与 Hymanson 1.9.9
  • Spring 3.1.1.RELEASE 与 Hymanson 1.9.9

as suggested here POSTing JSON to Spring MVC Controller Returns 400 Bad Request

正如这里所建议的POSTing JSON to Spring MVC Controller Returns 400 Bad Request

I made entries of MessageConverters also,

我也输入了 MessageConverters,

<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
        <bean class="org.springframework.http.converter.ResourceHttpMessageConverter"/>
        <bean class="org.springframework.http.converter.json.MappingHymansonHttpMessageConverter"/>
    </mvc:message-converters>
</mvc:annotation-driven>

Controller

控制器

@Controller
@RequestMapping(value="/todo", consumes="application/json", produces="application/json")
//@RequestMapping(value="/todo", consumes="text/plain", produces="application/json")
public class TodoRestService {
   Logger logger = LoggerFactory.getLogger(TodoService.class);
   @Autowired
   private TodoService todoService;

   @RequestMapping(value="/{id}", method= RequestMethod.GET)
   @ResponseBody public Todo find(@PathVariable("id") Long id) {
     Todo todo = todoService.find(id);
     return todo;
   }

   @RequestMapping(method=RequestMethod.POST)
   @ResponseBody public Todo create(@RequestBody Todo todo) {
   //public Todo create(@RequestBody String todo) {
   //public Todo create(@RequestParam("todo") String todo) {
     System.out.println(todo);
     todoService.create(newTodo);
     return newTodo;
  }
}

POJO

POJO

public class TODO {
  private String firstName;
  private String lastName;

  //getter setters
} 

I am using postman to POST the JSON

我正在使用邮递员发布 JSON

I have set Content-Type as application/json

我已将 Content-Type 设置为 application/json

form data ----- name = todo value = {"firstName":"nilam","lastName":"naik"}

表单数据 ----- name = todo value = {"firstName":"nilam","lastName":"naik"}

method = POST

方法 = POST

I am getting 400 Bad Request.

我收到 400 个错误的请求。

But If I changed data type of parameter annotated with @RequestBody from TODO to String then
I am getting something like,

但是,如果我将用@RequestBody 注释的参数的数据类型从 TODO 更改为 String,那么
我会得到类似的信息,

------WebKitFormBoundaryu6banLlTPiPudsBB
Content-Disposition: form-data; name="todo"

{"firstName":"nilam","lastName":"naik"}
------WebKitFormBoundaryu6banLlTPiPudsBB--

I also have Hymanson on my classpath.

我的类路径上也有Hyman逊。

If I changed attribute consumes from application/json to text/plain and

如果我将属性消耗从 application/json 更改为 text/plain 和

@RequestBody String todo then I get,

@RequestBody String todo 然后我得到,

{"firstName":"nilam","lastName":"naik"}

But I don't want to manually convert the String to Java Object. But I don't understand why @RequestBody is not able to convert my JSON data to Java Object.

但我不想手动将字符串转换为 Java 对象。但我不明白为什么@RequestBody 无法将我的 JSON 数据转换为 Java 对象。

pom.xml

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"      
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-      v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.orci</groupId>
    <artifactId>OrciMavenTutorial</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>OrciMavenTutorial Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <properties>
        <!-- <org.springframework.version>3.2.3.RELEASE</org.springframework.version> -->
        <org.springframework.version>3.1.1.RELEASE</org.springframework.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId> 
            <version>${org.springframework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId> 
            <version>${org.springframework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>

        <dependency>
             <groupId>org.hibernate</groupId>
             <artifactId>hibernate-entitymanager</artifactId>
             <version>4.2.2.Final</version>
        </dependency>

        <dependency>
             <groupId>javax.servlet</groupId>
             <artifactId>javax.servlet-api</artifactId>
             <version>3.0.1</version>
             <scope>provided</scope>
        </dependency>

        <dependency>
             <groupId>org.apache.derby</groupId>
             <artifactId>derbyclient</artifactId>
             <version>10.5.3.0_1</version>
        </dependency>

        <dependency>
              <groupId>org.apache.derby</groupId>
              <artifactId>derby</artifactId>
              <version>10.5.3.0_1</version>
        </dependency>

        <dependency>
              <groupId>org.slf4j</groupId>
              <artifactId>slf4j-api</artifactId>
              <version>1.7.7</version>
        </dependency>

        <dependency>
              <groupId>org.codehaus.Hymanson</groupId>
              <artifactId>Hymanson-core-asl</artifactId>
              <!-- <version>1.9.6</version> -->
              <!-- <version>1.4.2</version> -->
              <!-- <version>1.9.9</version> -->
              <version>1.9.7</version>
        </dependency>

       <dependency>
             <groupId>org.codehaus.Hymanson</groupId>
             <artifactId>Hymanson-mapper-asl</artifactId>
             <!-- <version>1.9.6</version> -->
             <!-- <version>1.4.2</version> -->
             <!-- <version>1.9.9</version> -->
             <version>1.9.7</version>
       </dependency>
 </dependencies>
 <build>
     <finalName>OrciMavenTutorial</finalName> 
 </build>

Please someone help me.

请有人帮助我。

回答by shazin

From the explanation you have given one thing is clear, You are using POSTMAN wrongly.

从您给出的解释中可以清楚地看出,您错误地使用了 POSTMAN。

You can not send a @RequestBodyannotated object in a form-data. Forms are handled using @ModelAttributeor @RequestParam(Multiple of this).

您不能@RequestBodyform-data. 使用@ModelAttribute@RequestParam(此的倍数)处理表单。

If you want to post a JSON to an Controller end point you must do like the following image;

如果您想将 JSON 发布到控制器端点,您必须像下图一样;

enter image description here

在此处输入图片说明

You must select POSTobviously and must set a header Content-Typeas application/json, finally you must select rawfrom the tabs and select JSONfrom the dropdown.

您必须POST明显选择并且必须将标题设置Content-Typeapplication/json,最后您必须raw从选项卡中进行选择并JSON从下拉列表中进行选择。

If you follow this your Controller method must work with Todoobject as @RequestBodyannotation and no need to use Stringand manually convert to object.

如果你遵循这个你的控制器方法必须使用Todo对象作为@RequestBody注释,并且不需要使用String和手动转换为对象。