2012年5月27日

Java 取得網頁資料

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;

public class HttpGetURL {


    public String str = "";
    public int line = 0;

    //public java.net.URL u;
    String url;
    String method;
    String code;
    
    public String allURL = "";
    
    public HttpGetURL() {}
    
    public void setURL(String url) {
        this.url = url;
        this.method = "GET";
        this.code = "";
        this.line = 0;
        this.allURL = url + "&" + Math.random();
        //HttpGetURL h = new HttpGetURL(url , "" , "GET");
        //str = h.str;
        //line = h.line;
    }

    public void setURL(String url, String code, String RequestMethod) {
        this.url = url;
        this.code = code;
        this.line = 0;
        this.method = RequestMethod;
        this.allURL = url + "?" + code + "&" + Math.random();
    }

    public void connect() {
        //StringBuffer s = new StringBuffer();
        String s = "";
        try {
            java.net.URL u = new java.net.URL(allURL);
            java.net.HttpURLConnection http = (java.net.HttpURLConnection) u.openConnection();

            http.setRequestMethod(method);
            //System.out.println(http.getRequestMethod());

            int n =  http.getResponseCode();

            //System.out.println(u.toString());
            //System.out.println(n + " " + HttpURLConnection.HTTP_OK);
            if (n == HttpURLConnection.HTTP_OK) {
                BufferedReader br = new BufferedReader(new InputStreamReader(
                        http.getInputStream(), "utf-8"));
                String tmp = null;

                while ((tmp = br.readLine()) != null) {
                    //s.append(tmp);
                    s += tmp;
                    line++;
                }

                str = s.toString();
            } else
                str = "Error";
        } catch (Exception ex) {
            ex.printStackTrace(System.out);
            //StackTraceElement[] em = ex.getStackTrace();
            str = "Error";
        }
        //s.delete(0, s.length());
    }
}
public class MAIN {
 public static void main(String[] args){
  HttpGetURL link = new HttpGetURL();
  
  String url = "http://www.google.com/";
  String code = "a=1";
  String RequestMethod = "GET";
  
  link.setURL(url, code, RequestMethod);
  link.connect();
  System.out.println(link.allURL);
  System.out.println(link.str);
 }
}

沒有留言: