我正在使用最新版本的java spring。 我尝试使用post方法和json body(contentType是application / json)来模拟调用以进行身份验证,但是当我的请求被我的java spring应用程序拦截时,正文是空的...并且我的authenticate方法抛出401 ..这个行为是正确。但空体不是。
我可以看到ngrep和一些功能,请放心,所有请求都已正确完成。
当我使用js客户端的curl,postman或ajax时我没有遇到此问题
@EnableAutoConfiguration
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class UserControllerImplTest {
@Test
public void testUserAuthenticateWitParams200() {
Map<String, Object> jsonAsMap = new HashMap<>();
jsonAsMap.put("email", "groschat.eu@gmail.com");
jsonAsMap.put("password", "groschat93**");
given().log().all()
.body(jsonAsMap)
.contentType("application/json; charset=UTF-8").
when()
.post(String.format("http://localhost:%s/api/users/authenticate", port))
.peek().
then()
.statusCode(is(200));
}
}
以下是来自peek()函数的日志:
Request method: POST
Request URI: http://localhost:53850/api/users/authenticate
Proxy: <none>
Request params: <none>
Query params: <none>
Form params: <none>
Path params: <none>
Headers: Accept=*/* Content-Type=application/json; charset=UTF-8
Cookies: <none>
Multiparts: <none>
Body:
{
"password": "groschat93**",
"email": "groschat.eu@gmail.com"
}
以下是chrome内部开发工具的请求
请求标题:
POST /api/users/authenticate HTTP/1.1
Host: back-spring.dev
Connection: keep-alive
Content-Length: 62
Origin: https://front.dev
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36
Content-type: application/json
Accept: */*
Referer: https://front.dev/
Accept-Encoding: gzip, deflate, br
Accept-Language: fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7
请求有效负载:
{"email":"martinbryan.eu@gmail.com","password":"groschat93**"}
答案 0 :(得分:0)
问题是Tomcat和标题Content-Type中的无用分号。 Tomcat无法使用分号读取内容类型,没有像charset一样的内容。所以当请求被读取时,服务器端的默认内容类型为text / plain。 RestAssured
所以我通过underow改变了tomcat,我不再使用放心了,而是WebTestClient。请参阅代码和pom.xml。预计不会出现这个问题。
b
我的pom.xml
@AutoConfigureWebTestClient
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@ContextConfiguration(
classes={
server_spring.Application.class,
server_spring.config.WebSecurityConfig.class,
server_spring.config.GlobalConfiguration.class,
server_spring.config.MvcConfig.class,
server_spring.config.WebConfig.class
})
public class UserControllerImplTest {
@Autowired
private WebTestClient webClient;
@Test
public void testWithAnotherMethod() {
Map<String, String> jsonMap = new HashMap();
jsonMap.put("email","martinbryan.eu@gmail.com");
jsonMap.put("password","groschat93**");
webClient
.post()
.uri("/api/users/authenticate")
.header("Origin","https://front.dev")
.header("Referer","https://front.dev")
.header("Host", "back-spring.dev")
.contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromObject(jsonMap))
.exchange()
.expectStatus()
.isOk();
}
}