Spring RestTemplate GET请求返回302状态

时间:2020-03-12 02:40:54

标签: java spring rest api http

我正在尝试使用Spring的RestTemplate组件使用第三方REST API。我尝试在外部REST API客户端(邮递员)上输入相同的请求-使用相同的URI和自定义标头,并且能够检索正确的数据。

但是,当我尝试使用RestTemplate镜像确切的请求时,它将返回我

        <html><head>
        <title>302 Found</title>
        </head><body>
        <h1>Found</h1>
        <p>The document has moved <a href="https://address/{path of endpoint}">here</a>.</p>
        <hr>
        <address>Apache/2.4.7 (Ubuntu) Server at address Port 80</address>
        </body></html>

这是我使用的代码示例:

        String uri = "http://address/{path of endpoint}";
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.set(someCustomHeaderKey, someCustomHeaderValue);
        HttpEntity<String> entity = new HttpEntity<String>(headers);
        ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class);

我已经阅读到Java不允许从一种协议重定向到另一种协议,例如,从http重定向到https,反之亦然。在此方面需要一些帮助。

2 个答案:

答案 0 :(得分:0)

默认情况下,RestTemplate将遵循重定向,但如果协议不同,则不会, 这就是您所看到的情况(从http重定向到https)。

有关更详细的说明以及使此工作有效的代码,请参见 HTTPURLConnection Doesn't Follow Redirect from HTTP to HTTPS

答案 1 :(得分:0)

我已经在本地计算机上尝试了您的代码,一切似乎都很好。 302状态码表示您的URI位置不同。 根据您的示例,应该在URI中使用https而不是Http

我已经尝试过如下代码

String uri = "https://jsonplaceholder.typicode.com/todos/1";
    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.set("link", "http/:");
    HttpEntity<String> entity = new HttpEntity<String>(headers);
    ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.GET, 
    entity, String.class);
    System.out.println(response);

控制台中的输出

<200,{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
},[Date:"Thu, 12 Mar 2020 03:45:44 GMT", Content-Type:"application/json; charset=utf-8", Content-Length:"83", Connection:"keep-alive", Set-Cookie:"__cfduid=d3104b8bbd25cbcb802977fc9183d559e1583984744; expires=Sat, 11-Apr-20 03:45:44 GMT; path=/; domain=.typicode.com; HttpOnly; SameSite=Lax", X-Powered-By:"Express", Vary:"Origin, Accept-Encoding", Access-Control-Allow-Credentials:"true", Cache-Control:"max-age=14400", Pragma:"no-cache", Expires:"-1", X-Content-Type-Options:"nosniff", Etag:"W/"53-hfEnumeNh6YirfjyjaujcOPPT+s"", Via:"1.1 vegur", CF-Cache-Status:"HIT", Age:"1747", Accept-Ranges:"bytes", Expect-CT:"max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"", Server:"cloudflare", CF-RAY:"572a862eab83d5e8-BOM"]>