當前位置:編程學習大全網 - 編程軟體 - Java請求壹個URL。獲取網站返回的數據。

Java請求壹個URL。獲取網站返回的數據。

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;?

}

  • 上一篇:lim(x趨向於∞)(3x-√9x^2-12x+1)為什麽不能直接在根號裏提取壹個x^2,直接得出答案呢
  • 下一篇:如何設置壹個div塊級元素水平居中?
  • copyright 2024編程學習大全網