在後臺程序中發送http請求並獲取響應數據
阿新 • • 發佈:2017-12-08
pri exception 讀取 except 分享圖片 () user trac log
一,在後臺程序中發送http請求獲取響應數據
1)以 http://libs.baidu.com/jquery/2.0.0/jquery.min.js 為例
二,
1)
String result=""; BufferedReader in = null; URL url = null; try { url = new URL("http://libs.baidu.com/jquery/2.0.0/jquery.min.js"); } catch (MalformedURLException e) { e.printStackTrace(); } //打開連接 URLConnection connection = url.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(); // 定義 BufferedReader輸入流來讀取URL的響應 in = new BufferedReader(new InputStreamReader( connection.getInputStream())); //寫出數據 String line; while ((line = in.readLine()) != null) { result += line; } //關流 in.close(); System.out.println(result);
三,
在後臺程序中發送http請求並獲取響應數據