【笔记】java http请求 HttpURLConnection 302 重定向

HttpURLConnection con = null;

try {
String url ="http://.。。。.com";
    // 获取文件流
con = (HttpURLConnection) new URL(url).openConnection();
con.setConnectTimeout(15000);
con.setReadTimeout(15000);
con.setInstanceFollowRedirects(false);
if (con.getResponseCode() == 302) {
//如果会重定向,保存302重定向地址,以及Cookies,然后重新发送请求(模拟请求)
String location = con.getHeaderField("Location");
con.disconnect();
url = location;
con = (HttpURLConnection) new URL(url).openConnection();
con.setConnectTimeout(15000);
con.setReadTimeout(15000);
}
}
catch (IOException e) {

}
posted @ 2019-08-08 15:50  helloyunyun8  阅读(4890)  评论(1编辑  收藏  举报