[Java]原生HttpURLConnection获得302重定向地址

2021-10-16 1011点热度 0人点赞 0条评论

如题,原生代码,使用HttpURLConnection请求时候,获取302 Follow Redirect重定向时候,获取需要重定向的地址。

注意需要加上这句 connection.setInstanceFollowRedirects(false);

否则会抛出java.net.SocketException: Unexpected end of file from server,而获取不到重定向地址。

String url = "http://www.example.com";
String postContent = "data=somedata";
HttpURLConnection connection = null;
connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);

//这句关键,否则connection.getResponseCode()这句会抛出异常: java.net.SocketException: Unexpected end of file from server
connection.setInstanceFollowRedirects(false);

connection.setConnectTimeout(60000 * 5);
connection.setReadTimeout(60000 * 5);
connection.getOutputStream().write(postContent.getBytes(StandardCharsets.UTF_8));

int responseCode = connection.getResponseCode();
if (responseCode == 302) {
    //重定向地址
    String redirctLocation = connection.getHeaderField("Location");
}

 

admin

这个人很懒,什么都没留下

文章评论

您需要 登录 之后才可以评论