【问题标题】:What should my postman post request look like? (body of the post request)我的邮递员邮寄请求应该是什么样的? (帖子请求的正文)
【发布时间】:2020-01-30 22:53:09
【问题描述】:
@PostMapping(path="/check/keywords")
    @RequestMapping(value = "/check/keywords", method = RequestMethod.POST)
    public int totalKeywords(@RequestBody String text,@RequestBody String[] keywords) throws Exception{
        System.out.println(text);
        System.out.println(keywords.length);
        return EssayGrader.totalKeywods(text);
    }

我已经为此请求尝试了各种不同的主体,但似乎没有任何效果。它会给出错误 400 或 500 内部服务器错误。 我想将字符串类型的文本和一些列表或数组形式的关键字从 Html 页面传递给我的 java 代码,以查看该文本字符串中有多少关键字。 你能帮帮我吗?

【问题讨论】:

    标签: java api post postman


    【解决方案1】:

    我相信在方法级别只能有一个 @RequestBody 注释参数。我建议将您的文本和关键字作为 JSON 文档发送到 HTTP 请求的请求正文中。例如。可能看起来像这样:

    { "text": "a simple text", "keywords": ["simple", "text"] }

    编写一个简单的 Java 类来保存这两个值,例如

    class Data {
       String text;
       String[] keywords;
    
       //don't forget getter + setter + noargs constructor
    }
    

    将您的方法更改为:

    @PostMapping(path="/check/keywords", consumes="application/json", produces="application/json")
    public int totalKeywords(@RequestBody Data data) {
        String text = data.getText();
        String[] keywords = data.getKeywords();
        // do whatever...
        return ...
    }
    

    当您发送 Postman POST 请求时,将 Content-Type 标头设置为 application/json!并确保您有 Jackson 库 - 以“自动”将 JSON 结构映射到 Java 类/对象 - 在您的类路径上(如果您使用 Spring Boot,则在导入此依赖项时应该已经是这种情况:

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

    希望这会有所帮助。祝你好运!

    【讨论】:

    • 嘿,这很有帮助,但我有一个问题。是否可以传递一个列表而不是那个数组?如果是怎么办?
    • 只需将类型从字符串数组更改为字符串列表,例如从String[] keywordsjava.util.List&lt;String&gt; keywords
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-11
    • 1970-01-01
    • 1970-01-01
    • 2019-07-31
    • 2017-05-16
    • 2017-06-17
    • 1970-01-01
    相关资源
    最近更新 更多