url下載檔案(重定向+cookie設定)
阿新 • • 發佈:2019-01-02
很多時候,下載檔案時會重定向,並且要求攜帶cookie才允許下載,這種情況下,如果讓下載支援重定向,並且設定cookie呢?下面的程式碼可以供大家參考。
public static void main(String[] args) throws Exception {
String cookie = "";
HttpURLConnection conn = null;
do {
URL url = new URL("***");
conn = (HttpURLConnection) url.openConnection();
//設定超時間為3秒
conn.setConnectTimeout(3*1000);
//防止遮蔽程式抓取而返回403錯誤
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
conn.setInstanceFollowRedirects(false);
if (cookie.length() != 0) {
conn.setRequestProperty("Cookie" , cookie);
}
int code = conn.getResponseCode();
if (code == HttpURLConnection.HTTP_MOVED_TEMP) {
for (int i = 1; i < conn.getHeaderFields().size(); i++) {
if (conn.getHeaderFieldKey(i).equalsIgnoreCase("set-cookie")) {
cookie += conn.getHeaderField(i) + ";" ;
}
}
}
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK)
break;
} while(true);
//得到輸入流
InputStream inputStream = conn.getInputStream();
byte[] buffer = new byte[1024];
int len = 0;
while((len = inputStream.read(buffer)) != -1) {
System.out.println(len);
}
if(inputStream!=null){
inputStream.close();
}
}