完成数据抓取!

This commit is contained in:
2022-03-16 15:58:00 +08:00
parent a27a1c8d85
commit f2c340d3cb
12 changed files with 399 additions and 9 deletions

View File

@@ -0,0 +1,13 @@
import com.cpic.xim.disaster_warning.WeatherDisasterWarningGrabber;
public class AppMain
{
public static void main( String[] args )
{
String cityCode = "101091103";
WeatherDisasterWarningGrabber.getWeatherDisasterWarningJSON( cityCode );
System.out.println( "1111" );
}
}

View File

@@ -0,0 +1,104 @@
package com.cpic.xim.disaster_warning;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.HttpURLConnection;
import java.util.zip.GZIPInputStream;
public class WeatherDisasterWarningGrabber
{
private static String QUERY_URL = "https://devapi.qweather.com/v7/warning/now?";
private static String USER_KEY = "fe9fa8eeeb6f4301a92541eed565dd15";
public static String getWeatherDisasterWarningJSON( String cityCode )
{
//拼接url字符串
String json = "";
String requestURL = QUERY_URL + "key=" + USER_KEY + "&location=" + cityCode;
//requestURL = "http://127.0.0.1:8000/ajax";
//链接用
HttpURLConnection connection = null;
URL url = null;
InputStream inputStream = null;
BufferedReader bufferedReader = null;
StringBuilder buffer = new StringBuilder();
try
{
url = new URL( requestURL );
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod( "GET" );
connection.setConnectTimeout( 15000 );
connection.setReadTimeout( 60000 );
connection.connect();
int reponseCode = connection.getResponseCode();
//如果responseCode为200说明访问成功
if ( connection.getResponseCode() == 200 )
{
inputStream = new GZIPInputStream( connection.getInputStream() );
bufferedReader = new BufferedReader( new InputStreamReader( inputStream, "UTF-8" ) );
//读出数据
String temp = bufferedReader.readLine();
while ( temp != null )
{
buffer.append( temp );
temp = bufferedReader.readLine();
}
json = buffer.toString();
}
}
catch ( MalformedURLException error )
{
error.printStackTrace();
}
catch ( IOException error )
{
System.out.println( "读取失败!" );
}
finally
{
if ( bufferedReader != null )
{
try
{
bufferedReader.close();
}
catch ( IOException error )
{
error.printStackTrace();
}
}
if ( inputStream != null )
{
try
{
inputStream.close();
}
catch ( IOException error )
{
error.printStackTrace();
}
}
connection.disconnect();
}
return json;
}
}