// 向對應的url地址發送http請求, 並獲取響應的json字符串
public String getHttpResponse(String url) {
// result用於接收鏈接響應的數據
String result = "";
// in用於讀取URL的響應
BufferedReader in = null;
try {
URL realUrl = new URL(url);
// 打開和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();
// 定義 BufferedReader輸入流來讀取URL的響應
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
// 經過http請求, 獲取的響應數據
return result;
}json