简体   繁体   中英

How to pass an array of primitives as Request in Postman

I was wondering what is the best way to pass a simple int[] array to a Spring Controller?

As of now it only worked when I am passing the values as a @RequestParam in the URL, however I would like to send them for example as a @RequestBody. How could I do that?

`

@PostMapping
public int acceptArray(@RequestParam int[] array) {

    if (array == null || array.length == 0) {
        throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "You entered an empty array");
    }

    return arraySolver.arraySolver(array);
}

`

Since I am kinda new a more detailed explanation would be appreciated:)

Thank you in advance for the help.

You can achieve that by passing the multiple arguments as query params like show in below. The controller is taking array as input and sum the elements and returns that. That is why for [1,2,3] it outputs 6.

在此处输入图像描述

To send it as request body you can just follow below code.

@PostMapping
    public int acceptArray(@RequestBody InputArrayRequest request) {

        if (request.getArray() == null || request.getArray().length == 0) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "You entered an empty array()");
        }

        return arraySolver.arraySolver(array);
    }

class InputArrayRequest {
    private int[] array;

    public int[] getArray() {
        return array;
    }
}

You can pass an array by specifying the same key multiple times in Body > form-data like in this screenshot: 邮递员截图

if you want an array of ints from a RequestBody

在此处输入图像描述

@PostMapping
public int acceptArray(@RequestBody int[] array) {
    if (array == null || array.length == 0) {
        throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "You entered an empty array()");
    }
    return Arrays.stream(array).sum();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM