我用的是之前參考網路上的 但是我程式碼太大 所以貼它的
讀取網頁過大時,"有時(同一個)"會出現錯誤:connection reset
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
public class SimpleURL2 {
public static void main(String[] args) throws IOException {
URL url = new URL("http://ithelp.ithome.com.tw/ironman7/app/index");
URLConnection conn = url.openConnection();
conn.connect();
String type = conn.getContentType();
System.out.println("Context: "+type);
FileWriter fw = new FileWriter("/Users/yfsun/Documents/Hi_Day10.txt");
InputStreamReader in = new InputStreamReader(conn.getInputStream(),"UTF-8");
int data = in.read();
while (data != -1){
System.out.print((char)data);
data = in.read();
fw.write(data);
fw.flush();
}
in.close();
fw.close();
}
}
你找的那個程式不太好
因為他讀網頁用 in.read
一次讀一個 character
可以改用Oracle 官方範例看看
import java.net.*;
import java.io.*;
public class URLReader {
public static void main(String[] args) throws Exception {
URL oracle = new URL("http://www.oracle.com/");
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}