Java請求一個URL。獲取網站返回的資料。
阿新 • • 發佈:2019-01-26
public static String SendGET(String url,String param){ String result="";//訪問返回結果 BufferedReader read=null;//讀取訪問結果 try { //建立url URL realurl=new URL(url+"?"+param); //開啟連線 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(); // 遍歷所有的響應頭欄位,獲取到cookies等 for (String key : map.keySet()) { System.out.println(key + "--->" + map.get(key)); } // 定義 BufferedReader輸入流來讀取URL的響應 read = new BufferedReader(new InputStreamReader( connection.getInputStream(),"UTF-8")); String line;//迴圈讀取 while ((line = read.readLine()) != null) { result += line; } } catch (IOException e) { e.printStackTrace(); }finally{ if(read!=null){//關閉流 try { read.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; }