標籤:
package com.sphere.service;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;public class QueryService { /** * 發起http get請求擷取網頁原始碼 * @param requestUrl * @return * @throws IOException */ private static String httpRequest(String requestUrl) throws IOException{ StringBuffer buffer = null; HttpURLConnection httpUrlConn = null; InputStream inputStream = null; InputStreamReader inputStreamReader = null; BufferedReader bufferedReader = null; try { // 建立串連 URL url = new URL(requestUrl); httpUrlConn = (HttpURLConnection)url.openConnection(); httpUrlConn.setDoInput(true); httpUrlConn.setRequestMethod("GET"); //擷取輸入資料流 inputStream = httpUrlConn.getInputStream(); // http://www.bjsubway.com/support/swzl/ 此網頁是gb2312編碼 inputStreamReader = new InputStreamReader(inputStream,"gb2312"); bufferedReader = new BufferedReader(inputStreamReader); // 讀取返回結果 buffer = new StringBuffer(); String str = null; while((str = bufferedReader.readLine())!= null){ buffer.append(str); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ //釋放資源,依次關閉流 if(bufferedReader != null){ bufferedReader.close(); } if(inputStreamReader != null){ inputStreamReader.close(); } if(inputStream != null){ inputStream.close(); } //釋放資源,關閉http串連 if(httpUrlConn != null){ httpUrlConn.disconnect(); } } return buffer.toString(); } public static void main(String[] args) throws IOException { String Url = "http://www.bjsubway.com/support/swzl/"; String htmlString = httpRequest(Url); System.out.println(htmlString); }}
Java 讀取網頁原始碼