简体   繁体   English

如何在 Postman 中将原语数组作为请求传递

[英]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?我想知道将简单的 int[] 数组传递给 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.截至目前,它仅在我将值作为 URL 中的 @RequestParam 传递时才起作用,但是我想将它们作为 @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.您可以通过将多个 arguments 作为查询参数传递来实现,如下所示。 The controller is taking array as input and sum the elements and returns that. controller 将数组作为输入并对元素求和并返回。 That is why for [1,2,3] it outputs 6.这就是 [1,2,3] 输出 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:您可以通过在Body > form-data中多次指定相同的键来传递数组,如以下屏幕截图所示: 邮递员截图

if you want an array of ints from a RequestBody如果你想要一个来自 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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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