bestlong 怕失憶論壇's Archiver

bestlong 發表於 2010-12-2 17:49

用 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]

Powered by Discuz! X1.5 Archiver   © 2001-2010 Comsenz Inc.