1. 程式人生 > >Java 傳送get請求獲得請求內容

Java 傳送get請求獲得請求內容

/**
 * 傳送get請求
 * @param url
 * @return
 */
public String sendGet(String url) {
    String result = "";
    BufferedReader in = null;
    try {
        String urlNameString = url;
        URL realUrl = new URL(urlNameString);
        // 開啟和URL之間的連線
        URLConnection connection = realUrl.openConnection();
        // 設定通用的請求屬性
        connection.setRequestProperty("accept", "*/*");
        connection.setRequestProperty("connection", "Keep-Alive");
        connection.setRequestProperty("user-agent",
                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        // 建立實際的連線
        connection.connect();
        // 獲取所有響應頭欄位
        Map<String, List<String>> map = connection.getHeaderFields();
        // 遍歷所有的響應頭欄位
        for (String key : map.keySet()) {
            System.out.println(key + "--->" + map.get(key));
        }
        // 定義 BufferedReader輸入流來讀取URL的響應
        in = new BufferedReader(new InputStreamReader(
                connection.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
            result += line;
        }
    } catch (Exception e) {
        System.out.println("傳送GET請求出現異常!" + e);
        e.printStackTrace();
    }
    // 使用finally塊來關閉輸入流
    finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (Exception e2) {
            e2.printStackTrace();
        }
    }
    return result;
}