0


Java Restful API接口获取请求头、请求体、以及设置响应状态码、应答(响应)体等

一、获取请求头

接口示例1:

    @PostMapping(value = "/wxPayNotify")
    public R<String> wxPayNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        weChatPaymentService.wxPayNotify(request, response);
        return R.ok();
    }

1、从 request 对象中获取请求头:

//语法:request.getHeader(请求头key)
String nonce = request.getHeader(wxPayConstant.getHeader_nonce());
String signature = request.getHeader(wxPayConstant.getHeader_signature());

二、获取请求体

1、从 request 对象中,使用缓冲流读取器、stream流等方式获取请求体

推荐写法一:

//写法一(推荐此写法):使用读取器配合java stream流,获取接口请求体
String requestBody = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
或者
String requestBody = request.getReader().lines().collect(Collectors.joining(SystemUtil.getProps().getProperty(SystemUtil.LINE_SEPARATOR)));

//写法二:读取完毕之后,记得关闭读取器,释放内存
        BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
        String line = null;
        StringBuilder requestBody = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            requestBody.append(line);
        }
        reader.close();

示例:

    @ApiOperation(value = "公共测试接口")
    @PostMapping("/testPublicApi")
    public CommonResult<String> testPublicApi(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = request.getReader().lines().collect(Collectors.joining(SystemUtil.getProps().getProperty(SystemUtil.LINE_SEPARATOR)));
        System.out.println("requestBody = " + requestBody);
        return success();
    }

控制台输出:

requestBody = {
    "address": "",
    "age": 0,
    "email": "",
    "id": 0,
    "price": 0,
    "userName": "张三"
}

2、通过 @RequestBody 映射到dto对象获取请求体

说明:
【1】一般我们会为 @PostMapping、@PutMapping、@PatchMapping 请求方式设置请求体,@GetMapping、@DeleteMapping 通过路径传参,不设置请求体(也可以设置请求体)
【2】一个rest接口可以有多个 @RequestParam,但只能有一个请求体对象 @RequestBody

示例:

    @ApiOperation(value = "公共测试接口")
    @PostMapping("/testPublicApi")
    public CommonResult<String> testPublicApi(HttpServletRequest request, HttpServletResponse response, @RequestBody PersonDto personDto) {
        System.out.println("personDto = " + personDto);
        return success();
    }

控制台输出:

personDto = PersonDto(id=0, userName=张三, email=, address=, age=0, price=0)

三、设置响应状态码、使用缓冲输出流以字节方式写入响应(应答)体:

            //设置响应码
            response.setStatus(HttpStatus.HTTP_INTERNAL_ERROR);

            //设置响应(应答)体,json格式
            Map<String, String> ackObj = Maps.newHashMap();
            ackObj.put("code", "FAIL");
            ackObj.put("message", "失败");
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            out.write(JSONObject.toJSONString(ackObj).getBytes());
            out.flush();
            out.close();

注意:
1、响应体数据是以字节的形式写入到输出流中
2、把响应体写入输出流之后,需要冲刷、关闭输出流对象

设置应答体之后,使用 http 请求获取 response 对象,读取请求接口的响应对象的输入流,读取应答体:

        HttpResponse execute = HttpUtil
                .createPost("http://xxx:6000/mpj/testDaily/testApiCalled")
                .setRest(true)
                .body(JSONUtil.toJsonStr(mapBody))
                .execute();
        int status = execute.getStatus();
        System.out.println("响应状态:" + status);

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(execute.bodyStream()));
        String responseBody = bufferedReader.lines().collect(Collectors.joining(SystemUtil.getProps().getProperty(SystemUtil.LINE_SEPARATOR)));
        System.out.println("responseBody:" + responseBody);

输出:

响应状态:210
responseBody:{"code":"FAIL","message":"失败"}

四、此处附带一个完整的示例代码,可供参考:

    @ApiOperation(value = "测试rest调用其他接口传入请求体")
    @PostMapping("/testHttpInvoke")
    public CommonResult<String> testHttpInvoke() {
        //请求接口携带请求体
        Map<String, Object> mapBody = new HashMap<>();
        mapBody.put("code", 400);
        mapBody.put("state", "FAIL");

        HttpResponse execute = HttpUtil
                .createPost("http://xxx:6000/mpj/testDaily/testApiCalled")
                .setRest(true)
                .body(JSONUtil.toJsonStr(mapBody))
                .execute();
        int status = execute.getStatus();
        System.out.println("响应状态:" + status);

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(execute.bodyStream()));
        String responseBody = bufferedReader.lines().collect(Collectors.joining(SystemUtil.getProps().getProperty(SystemUtil.LINE_SEPARATOR)));
        System.out.println("responseBody:" + responseBody);
        return success();
    }

    @ApiOperation(value = "测试request获得请求体-response设置响应(应答)体")
    @PostMapping("/testApiCalled")
    public void testApiCalled(HttpServletRequest request, HttpServletResponse response) throws IOException {

        //获取携带的请求体
        String requestBody = request.getReader().lines().collect(Collectors.joining(SystemUtil.getProps().getProperty(SystemUtil.LINE_SEPARATOR)));
        System.out.println("requestBody = " + requestBody);
        JSONObject jsonObject = JSONUtil.parseObj(requestBody);
        //根据请求体中的状态码,给予响应体
        if (200 == jsonObject.getInt("code")) {
            response.setStatus(200);
            BufferedOutputStream bo = new BufferedOutputStream(response.getOutputStream());
            Map<String, String> ackObj = Maps.newHashMap();
            ackObj.put("code", "SUCCESS");
            ackObj.put("message", "成功");
            bo.write(JSONUtil.toJsonStr(ackObj).getBytes());
            bo.flush();
            bo.close();
        } else {
            response.setStatus(400);
            BufferedOutputStream bo = new BufferedOutputStream(response.getOutputStream());
            Map<String, String> ackObj = Maps.newHashMap();
            ackObj.put("code", "FAIL");
            ackObj.put("message", "失败");
            bo.write(JSONUtil.toJsonStr(ackObj).getBytes());
            bo.flush();
            bo.close();
        }
    }

示例代码结果输出如下,符合预期:

requestBody = {"code":400,"state":"FAIL"}
响应状态:400
responseBody:{"code":"FAIL","message":"失败"}

总结:
1、使用缓冲读取器读取 request 的输入流对象,可以获得请求体
2、也可以使用 java stream 流获取请求体:

String requestBody = request.getReader().lines().collect(Collectors.joining(SystemUtil.getProps().getProperty(SystemUtil.LINE_SEPARATOR)));

3、通过 response 对象可以通过输出流对象,以字节的方式写入响应体

        //设置响应状态码、应答体(成功或失败)
        response.setStatus(210);
        BufferedOutputStream bo = new BufferedOutputStream(response.getOutputStream());
        Map<String, String> ackObj = Maps.newHashMap();
        ackObj.put("code", "FAIL");
        ackObj.put("message", "失败");
        bo.write(JSONUtil.toJsonStr(ackObj).getBytes());
        bo.flush();
        bo.close();

4、使用 http 请求接口,可以读取响应对象 HttpResponse 的输入流,从而获得响应体:

        HttpResponse execute = HttpUtil
                .createPost("http://xxx:6000/mpj/testDaily/testApiCalled")
                .setRest(true)
                .body(JSONUtil.toJsonStr(mapBody))
                .execute();
        int status = execute.getStatus();
        System.out.println("响应状态:" + status);

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(execute.bodyStream()));
        String responseBody = bufferedReader.lines().collect(Collectors.joining(SystemUtil.getProps().getProperty(SystemUtil.LINE_SEPARATOR)));
        System.out.println("responseBody:" + responseBody);

5、读取请求体是通过 inputStream(),写入响应体是通过 outputStream()

标签: java restful

本文转载自: https://blog.csdn.net/hkl_Forever/article/details/129646120
版权归原作者 拄杖忙学轻声码 所有, 如有侵权,请联系我们删除。

“Java Restful API接口获取请求头、请求体、以及设置响应状态码、应答(响应)体等”的评论:

还没有评论