1、使用HttpURLConnection
HttpURLConnection conn = (HttpURLConnection) new URL("http://192.168.1.200/6178dc0f47ec4fb8b0f01d87e13ea92d")
.openConnection();
conn.setInstanceFollowRedirects(false);
conn.setConnectTimeout(5000);
System.out.println(conn.getHeaderField("Location"));
2、使用RestTemplate
RestTemplate restTemplate = new RestTemplateBuilder()
.requestFactory(NoRedirectSimpleClientHttpRequestFactory.class)
.setConnectTimeout(Duration.ofMillis(3000))
.setReadTimeout(Duration.ofMillis(3000))
.build();
ResponseEntity<String> exchange = restTemplate.exchange(URI.create("http://192.168.1.200/6178dc0f47ec4fb8b0f01d87e13ea92d"),
HttpMethod.GET, HttpEntity.EMPTY, String.class);
System.out.println(exchange.getHeaders().getLocation().toString());
要禁止自动重定向写一个继承SimpleClientHttpRequestFactory的类,重写prepareConnection方法,把该属性设置为false;
public class NoRedirectSimpleClientHttpRequestFactory extends SimpleClientHttpRequestFactory {
@Override
protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
super.prepareConnection(connection, httpMethod);
connection.setInstanceFollowRedirects(false);
}
}