測試獲取免費天氣數據接口:http://www.weather.com.cn/data/sk/101190408.html
URL數據如下圖:

代碼部分:
package https;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class WeatherAPI {
public static void main(String[] args) throws Exception {
// WeatherAPI.json("北京");
System.out.println(getHttpRequestData("http://www.weather.com.cn/data/sk/101190408.html"));
}
public static String getHttpRequestData(String urlPath) {
// 首先抓取異常並處理
String returnString = "1";
try{
// 代碼實現以GET請求方式為主,POST跳過
/** 1 GET方式請求數據 start*/
// 1 創建URL對象,接收用戶傳遞訪問地址對象鏈接
URL url = new URL(urlPath);
// 2 打開用戶傳遞URL參數地址
HttpURLConnection connect = (HttpURLConnection) url.openConnection();
// 3 設置HTTP請求的一些參數信息
connect.setRequestMethod("GET"); // 參數必須大寫
connect.connect();
// 4 獲取URL請求到的數據,並創建數據流接收
InputStream isString = connect.getInputStream();
// 5 構建一個字符流緩沖對象,承載URL讀取到的數據
BufferedReader isRead = new BufferedReader(new InputStreamReader(isString));
// 6 輸出打印獲取到的文件流
String str = "";
while ((str = isRead.readLine()) != null) {
str = new String(str.getBytes(),"UTF-8"); //解決中文亂碼問題
// System.out.println("文件解析打印:");
// System.out.println(str);
returnString = str;
}
// 7 關閉流
isString.close();
connect.disconnect();
// 8 JSON轉List對象
// do somthings
}catch(Exception e){
e.printStackTrace();
}
return returnString;
}
}
解析后控制台打印:

