通过springboot 提供 application/json 的POST请求

1. 通过springboot 提供 application/json 的POST请求

在Spring Boot中,可以通过使用@RequestBody注释来实现将JSON作为请求主体发送到控制器方法中。以下是一个使用@RequestBody注释的示例控制器方法:

@PostMapping("/myendpoint")
public ResponseEntity<MyResponse> myEndpoint(@RequestBody MyRequest request) {
    // 处理请求并生成响应
    MyResponse response = /*...*/;
    return ResponseEntity.ok(response);
}

在这个例子中,MyRequestMyResponse是自定义Java类,用于表示请求和响应的JSON数据。@RequestBody注释告诉Spring Boot将POST请求的JSON主体解析成一个MyRequest对象,然后传递到myEndpoint方法中进行处理。

然后,您可以在客户端上使用任何HTTP库来发送POST请求,例如curl或Java的HttpURLConnection类:

curl -X POST -H "Content-Type: application/json" -d '{"name": "John Doe", "age": 42}' http://localhost:8080/myendpoint
URL url = new URL("http://localhost:8080/myendpoint");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
con.setDoOutput(true);

String jsonInputString = /*...*/;

try(OutputStream os = con.getOutputStream())
{
    byte[] input = jsonInputString.getBytes("utf-8");
    os.write(input, 0, input.length);
}

try(BufferedReader br = new BufferedReader(
        new InputStreamReader(con.getInputStream(), "utf-8")))
{
    StringBuilder response = new StringBuilder();
    String responseLine = null;
    while ((responseLine = br.readLine()) != null) {
        response.append(responseLine.trim());
    }
    System.out.println(response.toString());
}

请注意,客户端发送的JSON必须与控制器方法中使用的Java类相匹配。如果JSON数据格式不正确,服务器将返回400错误。

类似文章

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注