resttemplate收到的响应不是json格式的

a64a0gku  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(481)

在用spock为用jwt保护的restapi编写集成测试时,我遇到了响应内容类型的问题。对于 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,application/*+json,/]
如果我只设置application/json。即使在successfulyauthentication方法中将contenttype设置为json也无济于事。
知道我做错了什么吗?

beq87vna

beq87vna1#

抱歉耽搁了。
是的,问题是回答的论点。我一直在研究整个React,而不是只研究身体。
看起来应该是 def body = parseResponse(response.body) 谢谢你花时间调查!!

相关问题