欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-05-29 10:14:07
HttpURLConnection con = null;try { String url ="http://.。。。.com"; // 获取文件流 con = (HttpURLConnection) new URL(url).openConnection(); con.setConnectTime ......
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) {

}