最近有個需求是需要在java中以GET方式去請求網址獲取返回數據,就寫出來共享一下。直接上碼
/* get方式訪問網址 */ public static String sendGet(String url, String param) { String result = ""; BufferedReader in = null; try { String urlName = url + "?" + param; URL realUrl = new URL(urlName); //打開和URL之間的連接 URLConnection conn = realUrl.openConnection(); //設置通用的請求屬性 conn.setRequestProperty("accept", "charset=UTF-8"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); //建立實際的連接 conn.connect(); //定義BufferedReader輸入流來讀取URL的響應 in = new BufferedReader(new InputStreamReader(conn.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 (IOException ex) { ex.printStackTrace(); } } return result; }
//提供主方法,測試發送GET請求 public static void main(String args[]) throws ParseException { //發送GET請求 String s = STicketController.sendGet("https://www.baidu.com", "q=泰山"); //String轉爲JSON JSONObject jsonObj = (JSONObject)(new JSONParser().parse(s)); System.out.println(jsonObj.get("data")); }
注意:1、如果String不轉爲JSON,result裏面的中文是unicode格式的(也可能是我的請求問題)。
2、param直接以字符串格式傳入即可。