2012年10月24日水曜日

【Java TIPS】Webページにアクセスして内容を取得する

import java.io.*;
import java.net.*;

public class GetTest {

    public static void main(String[] args) {
        try{
            //プロキシサーバの設定(必要に応じて)
            //System.setProperty("http.proxyHost","proxy.example");
            //System.setProperty("http.proxyPort","0000");
            //System.setProperty("http.proxyHost","proxy.example");
            //System.setProperty("http.proxyPort","0000");
           
            //HTTPリクエスト
            URL url = new URL("http://www.example/index.html");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                       
            //ステータスコード
            System.out.printf("%d %s\n",connection.getResponseCode(),

                                              connection.getResponseMessage());
           
            //レスポンスボディの表示
            BufferedReader br = new BufferedReader(new InputStreamReader(

                                                   connection.getInputStream(),"UTF-8"));
            String line = null;
            while ((line = br.readLine()) != null){
                System.out.println(line);
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

0 件のコメント:

コメントを投稿