如何解决RestTemplate 收到的响应不在 json 中
在 spock 中为使用 JWT 保护的 rest api 编写集成测试时,我遇到了响应内容类型的问题。对于 swagger 或 postman 来说没有问题。它只发生在集成测试中。
从测试开始登录:
18:24:57.101 [Test worker] DEBUG org.springframework.web.client.RestTemplate - HTTP POST http://localhost:8080/login
18:24:57.110 [Test worker] DEBUG org.springframework.web.client.RestTemplate - Accept=[text/plain,application/json,application/*+json,*/*]
18:24:57.138 [Test worker] DEBUG org.springframework.web.client.RestTemplate - Writing [{login=test,password=test}] as "application/json"
18:24:57.282 [Test worker] DEBUG org.springframework.web.client.RestTemplate - Response 200 OK
18:24:57.284 [Test worker] DEBUG org.springframework.web.client.RestTemplate - Reading to [java.lang.String] as "application/json;charset=ISO-8859-1"
这是来自服务器的响应
<200,###BODY###,[Vary:"Origin","Access-Control-Request-Method","Access-Control-Request-Headers",Authorization:###JWT_TOKEN###,X-Content-Type-Options:"nosniff",X-XSS-Protection:"1; mode=block",Cache-Control:"no-cache,no-store,max-age=0,must-revalidate",Pragma:"no-cache",Expires:"0",X-Frame-Options:"DENY",Content-Type:"application/json;charset=ISO-8859-1",Transfer-Encoding:"chunked",Date:"Sun,31 Jan 2021 16:58:29 GMT",Keep-Alive:"timeout=60",Connection:"keep-alive"]>
结果我显然收到了:
无法确定当前字符,它不是字符串、数字、数组或对象
这是我的测试:
def 'should login player' (){
given:
def credentials = [
"login" : "test","password": "test"
]
when:
def response = sendPost(credentials,"login",String.class)
def body = parseResponse(response)
then:
(body.Authentication as String).contains("Bearer")
}
def rest = new RestTemplate()
def headers = new HttpHeaders()
def url = "http://localhost:8080/"
def setup() {
rest.messageConverters.add(new FormHttpMessageConverter())
rest.messageConverters.add(new StringHttpMessageConverter())
headers.setContentType(APPLICATION_JSON)
headers.remove("Accept")
headers.add("Accept",APPLICATION_JSON_VALUE)
}
def sendPost(def body,String endpoint,Class returnType) {
def httpEntity = new HttpEntity<>(body,headers)
rest.postForEntity((url + endpoint),httpEntity,returnType)
}
不明白为什么在日志中我可以看到 Accept=[text/plain,/]
如果我只设置 application/json。 即使在 successyAuthentication 方法中将 contentType 设置为 json 也无济于事。
知道我做错了什么吗?
解决方法
抱歉耽误了。
是的,问题是 parseResponse 的参数。我一直在研究整个响应,而不仅仅是正文。
它应该看起来像 def body = parseResponse(response.body)
感谢您花时间调查它!!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。