如何在 Spring Test 的 RestTemplate 中创建带有 json 内容类型标头的纯 http 请求?

问题描述 投票:0回答:1

有一个简单的rest/api spring boot项目,当架构输入错误时需要测试,如下所示:

curl -D- -X POST -H 'Content-Type: application/json' \
  -d 'BAD-SCHEMA-$@#%{[|!/-' \
  http://127.0.0.1:8080/auth/sign-up

我尝试在测试计划中使用原生 JUnit 5 的

RestTemplate
进行 Spring 测试:

    @Test
    public void signUpBadInputSchemaValidation() {
        /*
        curl -D- -X POST -H 'Content-Type: application/json' \
        -d 'BAD-SCHEMA-$@#%{[|!/-' \
        http://127.0.0.1:8080/auth/sign-up
        */

        // Prepare request headers
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // Prepare request body
        HttpEntity<String> requestEntity = new HttpEntity<>("BAD-SCHEMA-$@#%{[|!/-");

        // Create http request
        ResponseEntity<Object> responseEntity = restTemplate.exchange(
            "http://127.0.0.1:" + port + "/auth/sign-up",
            HttpMethod.POST, requestEntity, Object.class);

        // Response validation
        assertThat(responseEntity.getStatusCode())
            .isEqualTo(HttpStatus.UNPROCESSABLE_ENTITY);
    }

但是

restTemplate
会自动将
Content-Type
更改为
text/plain
,但需要保留
application/json

我尝试更改测试请求中的端口并使用 netcat 进行嗅探:

ncat -vlp 9999
Ncat: Version 7.80 ( https://nmap.org/ncat )
Ncat: Listening on :::9999
Ncat: Listening on 0.0.0.0:9999
Ncat: Connection from 127.0.0.1.
Ncat: Connection from 127.0.0.1:54478.
POST /system/access/first HTTP/1.1
Accept: application/json, application/*+json
Content-Type: text/plain;charset=UTF-8
User-Agent: Java/17.0.8
Host: 127.0.0.1:9999
Connection: keep-alive
Content-Length: 21

BAD-SCHEMA-$@#%{[|!/-

restTemplate
将标题更改为
Content-Type: text/plain;charset=UTF-8

如何使用

application/json
以纯文本正文保留
restTemplate
来执行安全测试?

java spring-boot unit-testing security resttemplate
1个回答
0
投票

这是因为您错过了将

application/json
HttpHeaders
配置为
HttpEntity
。更改为以下内容应该可以解决问题:

 HttpEntity<String> requestEntity = new HttpEntity<>("BAD-SCHEMA-$@#%{[|!/-", headers);

© www.soinside.com 2019 - 2024. All rights reserved.