用 Java Socket 抓取氣象預報網頁
[code]import java.io.*;
import java.net.Socket;
class GetWeatherReport {
public static void main(String args[]) {
String url = "/V6/forecast/taiwan/W01.htm";
try {
Socket socket = new Socket("www.cwb.gov.tw", 80);
DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
DataInputStream dis = new DataInputStream(socket.getInputStream());
dos.writeBytes("GET " + url + " HTTP/1.0\n\n");
dos.flush();
String sTmp;
// 去掉表頭
while((sTmp = dis.readLine()) != null) {
if(sTmp.trim().length() == 0) {
break;
}
}
byte abyte0[] = new byte[1024];
boolean flag = false;
int k;
for(sTmp = new String(""); (k = dis.read(abyte0)) > 0; sTmp = sTmp + new String(abyte0, 0, k,"Big5"));
sTmp = sTmp.substring(sTmp.indexOf("pre") + 5);
sTmp = sTmp.substring(0, sTmp.lastIndexOf("pre") - 2);
System.out.println(sTmp);
} catch (Exception e) {
e.printStackTrace();
}
}
}[/code]
頁:
[1]