我想用http GET调用RestTemplate并检索状态代码和重定向的url(如果有的话)。
如何实现?
答案 0 :(得分:1)
HttpClient
创建Apache RedirectStrategy
,您可以在重定向时拦截中间响应。HttpComponentsClientHttpRequestFactory
和新的Apache HttpClient
。有关详细信息,请查看org.apache.http.client.RedirectStrategy。或者重复DefaultRedirectStrategy
,如以下示例所示:
CloseableHttpClient httpClient = HttpClientBuilder
.create()
.setRedirectStrategy( new DefaultRedirectStrategy() {
@Override
public boolean isRedirected(HttpRequest request, HttpResponse response,
HttpContext context) throws ProtocolException {
System.out.println(response);
// If redirect intercept intermediate response.
if (super.isRedirected(request, response, context)){
int statusCode = response.getStatusLine().getStatusCode();
String redirectURL = response.getFirstHeader("Location").getValue();
System.out.println("redirectURL: " + redirectURL);
return true;
}
return false;
}
})
.build();
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
RestTemplate restTemplate = new RestTemplate(factory);
.......
答案 1 :(得分:1)
var responseEntity = restTemplate.exchange("someurl", HttpMethod.GET, null, Object.class);
HttpHeaders headers = responseEntity.getHeaders();
URI location = headers.getLocation();
location.toString();
答案 2 :(得分:0)
使用Spring并覆盖SimpleClientHttpRequestFactory中的prepareConnection()...
RedirectMatch 301 "^/$" "/FormTest/register/"
RedirectMatch 301 "^/index\.html$" "/FormTest/register/"
RedirectMatch 301 "^/index\.php$" "/FormTest/register/"