package com.czk.test.io;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;
/**
* 下載任意URL對應的網頁html代碼
*
* @author czk
*
* @time:2019年8月2日
*/
public class DownloadWebPage4UrlConnection {
public static String download(String httpUrl) throws IOException {
URL url = new URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.connect();
BufferedInputStream bis = null;
ByteOutputStream bos = null;
try {
InputStream is = connection.getInputStream();
bis = new BufferedInputStream(is);
bos = new ByteOutputStream();
int b = 0;
byte[] byArr = new byte[1024];
while ((b = bis.read(byArr)) != -1) {
bos.write(byArr, 0, b);
}
return new String(bos.toByteArray(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (bis != null) {
bis.close();
}
if (bos != null) {
bos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public static void main(String[] args) throws IOException {
String httpUrl = "http://www.baidu.com";
String content=download(httpUrl);
System.out.println(content);
}
}
Java之下載相關網頁到本地
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.