jay patel
jay patel

Reputation: 21

What should my postman post request look like? (body of the post request)

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

I have tried various different body for this request but nothing seems to work. Either it gives error 400 or 500 internal server error. I want to pass a text of type string and some keywords in the form of list or array from the Html page to my java code to see how many keywords are there in that text string. Can you please help me.

Upvotes: 0

Views: 1280

Answers (1)

Tommy Brettschneider
Tommy Brettschneider

Reputation: 1490

I believe there can only be a single @RequestBody annotated param at method level. I recommend to send your text and the keywords as a JSON document in the requestbody of your HTTP request. E.g. could look like this:

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

Write a simple Java class that holds these two values, e.g.

class Data {
   String text;
   String[] keywords;

   //don't forget getter + setter + noargs constructor
}

Change your method to:

@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 ...
}

Set Content-Type header to application/json when you send your Postman POST-request! And ensure that you have the Jackson library - to "automatically" map JSON structures to Java classes/objects - on your classpath (if you use Spring Boot that should be already the case when you import this dependency:

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

Hope this helps. Good luck!

Upvotes: 1

Related Questions