前言
中国地震台数据主要观测的是国内的地震,少量国外等级较高地震,访问太过频繁会被封IP
美国地震台数据观测全球,有API提供调取,鼓励调取,频繁获取也不会被封IP
欧洲地震台数据观测全球,采用webscoket的方式接入数据,连接上被动接受数据
中国地震台地址:点击前往
美国地震台地址:点击前往
欧洲地震台网:点击前往
一、中国地震台网CHN
定时获取数据,获取最新一页的地震数据,获取间隔可以设置少一些!
String urlDevicess = "http://www.ceic.ac.cn/ajax/speedsearch?num=2&&page=1";
String sss = HttpClientUtils.get(urlDevicess);
JSONObject jsonDevicess = JSON.parseObject(sss.replaceAll("\\(", "").replaceAll("\\)", ""));
List<Map<String, Object>> deviceListss = (List)jsonDevicess.get("shuju");
Iterator var5ss = deviceListss.iterator();
//循环获取数据
while(var5ss.hasNext()) {
Map<String, Object> devicess = (Map)var5ss.next();
String o_timess = String.valueOf(devicess.get("O_TIME"));//日期
String LOCATION_Css = String.valueOf(devicess.get("LOCATION_C"));//发生位置
String Mss = String.valueOf(devicess.get("M"));//震级
String EPI_LATss = String.valueOf(devicess.get("EPI_LAT"));//纬度
String EPI_LONss = String.valueOf(devicess.get("EPI_LON"));//经度
String EPI_DEPTHss = String.valueOf(devicess.get("EPI_DEPTH"));//深度
//判断数据库是否存在,防止重复入库
QueryWrapper queryWrapperss = new QueryWrapper();
queryWrapperss.eq("time", o_timess);
queryWrapperss.eq("address", LOCATION_Css);
List<EarthquakeReal> listss = this.EarthquakeRealService.list(queryWrapperss);
//匹配规则:时间差小于3分钟,经纬度小于2度,震级小于0.5级
if(listss.size() == 0){
EarthquakeReal tEarthquakeRealss = new EarthquakeReal();
tEarthquakeRealss.setGrade(Double.valueOf(Mss));
tEarthquakeRealss.setTime(o_timess);
tEarthquakeRealss.setLat(Double.valueOf(EPI_LATss));
tEarthquakeRealss.setLon(Double.valueOf(EPI_LONss));
tEarthquakeRealss.setDepth(Double.valueOf(EPI_DEPTHss));
tEarthquakeRealss.setAddress(LOCATION_Css);
tEarthquakeRealss.setCreatetime(DateUtil.getTodays("yyyy-MM-dd HH:mm:ss"));
tEarthquakeRealss.SetCountry("CHN");
this.EarthquakeRealService.save(tEarthquakeRealss);
}
}
二、美国地震台网USA
根据日期(中国北京时间)经纬度和范围大小获取数据
String today = DateUtil.getToday();
String urlDevice = "http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&latitude=38&longitude=84&maxradiuskm=9999&starttime=" + today;
String s = HttpClientUtils.get(urlDevice);
JSONObject jsonDevice = JSON.parseObject(s);
List<Map<String, Object>> deviceList = (List) jsonDevice.get("features");
new DecimalFormat("0.");
Iterator var7 = deviceList.iterator();
while (var7.hasNext()) {
Map<String, Object> device = (Map) var7.next();
JSONObject properties = (JSONObject) device.get("properties");
JSONObject geometry = (JSONObject) device.get("geometry");
List<Map<String, Object>> coordinates = (List) geometry.get("coordinates");
String time = String.valueOf(properties.get("time"));
String o_time = DateUtil.timeStamp2Date(time, "yyyy-MM-dd HH:mm:ss");
String LOCATION_C = String.valueOf(properties.get("place"));
String M = String.valueOf(properties.get("mag"));
String EPI_LON = String.valueOf(coordinates.get(0));
String EPI_LAT = String.valueOf(coordinates.get(1));
String depth = String.valueOf(coordinates.get(2));
EarthquakeReal tEarthquakeReal = new EarthquakeReal();
tEarthquakeReal.setGrade(Double.valueOf(M));
tEarthquakeReal.setTime(o_time);
tEarthquakeReal.setLat(Double.valueOf(EPI_LAT));
tEarthquakeReal.setLon(Double.valueOf(EPI_LON));
tEarthquakeReal.setDepth(Double.valueOf(depth));
tEarthquakeReal.setAddress(LOCATION_C);
tEarthquakeReal.setCreatetime(DateUtil.getTodays("yyyy-MM-dd HH:mm:ss"));
tEarthquakeReal.SetCountry("USA");
this.EarthquakeRealService.save(tEarthquakeReal);
}
三、欧洲地震台网EUR
通过websocket连接,地址:
wss://www.seismicportal.eu/standing_order/websocket
int socket = 0;//判断socket是否连接成功
WebSocketClient webSocketClient = new WebSocketClient(new URI("wss://www.seismicportal.eu/standing_order/websocket"), new Draft_6455()) {
//连接服务端时触发
@Override
public void onOpen(ServerHandshake handshakedata) {
System.out.println("websocket客户端和服务器连接成功");
socket=1;
}
//收到服务端消息时触发
@Override
public void onMessage(String message) {
System.out.println("websocket客户端收到消息"+ message);
//开始解析数据
Map<String,Class<?>> classMap = new HashMap<String,Class<?>>();
JSONObject jsonObject = JSONObject.fromObject(message);
Root root = (Root) JSONObject.toBean(jsonObject, Root.class,classMap);//将json字符串转换为对象
Properties properties = root.getData().getProperties();
double lat = properties.getLat();//纬度
double lon = properties.getLon();//经度
double mag = properties.getMag();//震级
String time = properties.getTime();//时间
int depth = properties.getDepth();//深度
String flynnRegion = properties.getFlynn_region();//地震区域
//日期格式转换为中国时间
//进行转化时区
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.US);
Date myDate = null;
try {
myDate = dateFormat.parse (time.replace("Z","+0000"));
} catch (ParseException e) {
throw new RuntimeException(e);
}
//转换为年月日时分秒
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formatTime = df.format(myDate);
boolean inChina = IsInChinaUtil.isInChina(Double.valueOf(lat), Double.valueOf(lon));
System.out.println(lat+"-"+lon);
System.out.println("是否在中国境内"+inChina);
if(inChina){
//在中国境内
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("time", formatTime);
queryWrapper.eq("address", flynnRegion);
queryWrapper.eq("country", "EUR");
List<EarthquakeReal> listEUR = earthquakeRealService.list(queryWrapper);
if(listEUR.size()==0){
//入库在中国境内的地震-欧洲地震数据源
EarthquakeReal tEarthquakeReal = new EarthquakeReal();
tEarthquakeReal.setGrade(Double.valueOf(mag));
tEarthquakeReal.setTime(formatTime);
tEarthquakeReal.setLat(Double.valueOf(lat));
tEarthquakeReal.setLon(Double.valueOf(lon));
tEarthquakeReal.setDepth(Double.valueOf(depth));
tEarthquakeReal.setAddress(flynnRegion);
tEarthquakeReal.setCreatetime(DateUtil.getTodays("yyyy-MM-dd HH:mm:ss"));
tEarthquakeReal.SetCountry("EUR");
earthquakeRealService.save(tEarthquakeReal);
}
}
}
//和服务端断开连接时触发
@Override
public void onClose(int code, String reason, boolean remote) {
socket=0;
System.out.println("websocket客户端退出连接");
}
//连接异常时触发
@Override
public void onError(Exception ex) {
socket=0;
System.out.println("websocket客户端和服务器连接发生错误"+ex.getMessage());
}
};
webSocketClient.connect();
四、相关工具类
实体类
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
@TableName("biz_earthquake_real")
public class EarthquakeReal implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(
value = "id",
type = IdType.AUTO
)
private Integer id;
@TableField("grade")
private Double grade;//地震级数
@TableField("lon")
private Double lon;//经度
@TableField("lat")
private Double lat;//纬度
@TableField("time")
private String time;//发生时间
@TableField("depth")
private Double depth;//深度
@TableField("address")
private String address;//地点
@TableField("createtime")
private String createtime;//创建时间
@TableField("country")
private String country;//国家
public EarthquakeReal() {
}
public String getCountry() {
return this.country;
}
public void SetCountry(String country) {
this.country = country;
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public Double getGrade() {
return this.grade;
}
public void setGrade(Double grade) {
this.grade = grade;
}
public Double getLon() {
return this.lon;
}
public void setLon(Double lon) {
this.lon = lon;
}
public Double getLat() {
return this.lat;
}
public void setLat(Double lat) {
this.lat = lat;
}
public String getTime() {
return this.time;
}
public void setTime(String time) {
this.time = time;
}
public Double getDepth() {
return this.depth;
}
public void setDepth(Double depth) {
this.depth = depth;
}
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCreatetime() {
return this.createtime;
}
public void setCreatetime(String createtime) {
this.createtime = createtime;
}
public String toString() {
return "EarthquakeReal{id=" + this.id + ", grade=" + this.grade + ", lon=" + this.lon + ", lat=" + this.lat + ", time=" + this.time + ", depth=" + this.depth + ", address=" + this.address + ", createtime=" + this.createtime + "}";
}
}
判断经纬度是否在中国境内
public class IsInChinaUtil {
public static boolean isInChina(double lat, double lon) {
double[] lats = {
3.86, 53.55};
double[] lons = {
73.66, 135.05};
if (lat > lats[0] && lat < lats[1] && lon > lons[0] && lon < lons[1]) {
return true;
}
return false;
}
}
HTTP工具类
扫描二维码关注公众号,回复: 15080375 查看本文章
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.CharArrayBuffer;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class HttpClientUtils {
public HttpClientUtils() {
}
public static String get(String url) {
String result = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet get = new HttpGet(url);
CloseableHttpResponse response = null;
try {
response = httpClient.execute(get);
if (response != null && response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
result = entityToString(entity);
}
String var17 = result;
return var17;
} catch (IOException var15) {
var15.printStackTrace();
} finally {
try {
httpClient.close();
if (response != null) {
response.close();
}
} catch (IOException var14) {
var14.printStackTrace();
}
}
return null;
}
public static String getMap(String url, Map<String, String> map) {
String result = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
List<NameValuePair> pairs = new ArrayList();
Iterator var5 = map.entrySet().iterator();
while(var5.hasNext()) {
Map.Entry<String, String> entry = (Map.Entry)var5.next();
pairs.add(new BasicNameValuePair((String)entry.getKey(), (String)entry.getValue()));
}
CloseableHttpResponse response = null;
try {
URIBuilder builder = new URIBuilder(url);
builder.setParameters(pairs);
HttpGet get = new HttpGet(builder.build());
response = httpClient.execute(get);
if (response != null && response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
result = entityToString(entity);
}
String var28 = result;
return var28;
} catch (URISyntaxException var22) {
var22.printStackTrace();
} catch (ClientProtocolException var23) {
var23.printStackTrace();
} catch (IOException var24) {
var24.printStackTrace();
} finally {
try {
httpClient.close();
if (response != null) {
response.close();
}
} catch (IOException var21) {
var21.printStackTrace();
}
}
return null;
}
public static String postMap(String url, Map<String, String> map) {
String result = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
List<NameValuePair> pairs = new ArrayList();
Iterator var6 = map.entrySet().iterator();
while(var6.hasNext()) {
Map.Entry<String, String> entry = (Map.Entry)var6.next();
pairs.add(new BasicNameValuePair((String)entry.getKey(), (String)entry.getValue()));
}
CloseableHttpResponse response = null;
try {
post.setEntity(new UrlEncodedFormEntity(pairs, "UTF-8"));
response = httpClient.execute(post);
if (response != null && response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
result = entityToString(entity);
}
String var27 = result;
return var27;
} catch (UnsupportedEncodingException var21) {
var21.printStackTrace();
} catch (ClientProtocolException var22) {
var22.printStackTrace();
} catch (IOException var23) {
var23.printStackTrace();
} finally {
try {
httpClient.close();
if (response != null) {
response.close();
}
} catch (IOException var20) {
var20.printStackTrace();
}
}
return null;
}
public static String postJson(String url, String jsonString) {
String result = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
CloseableHttpResponse response = null;
try {
post.setEntity(new ByteArrayEntity(jsonString.getBytes("UTF-8")));
response = httpClient.execute(post);
if (response != null && response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
result = entityToString(entity);
}
String var24 = result;
return var24;
} catch (UnsupportedEncodingException var20) {
var20.printStackTrace();
} catch (ClientProtocolException var21) {
var21.printStackTrace();
} catch (IOException var22) {
var22.printStackTrace();
} finally {
try {
httpClient.close();
if (response != null) {
response.close();
}
} catch (IOException var19) {
var19.printStackTrace();
}
}
return null;
}
private static String entityToString(HttpEntity entity) throws IOException {
String result = null;
if (entity != null) {
long lenth = entity.getContentLength();
if (lenth != -1L && lenth < 2048L) {
result = EntityUtils.toString(entity, "UTF-8");
} else {
InputStreamReader reader1 = new InputStreamReader(entity.getContent(), "UTF-8");
CharArrayBuffer buffer = new CharArrayBuffer(2048);
char[] tmp = new char[1024];
int l;
while((l = reader1.read(tmp)) != -1) {
buffer.append(tmp, 0, l);
}
result = buffer.toString();
}
}
return result;
}
}
pom
<dependency>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2</artifactId>
<version>2.0.22</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.7</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.14</version>
</dependency>
<dependency>
<groupId>org.java-websocket</groupId>
<artifactId>Java-WebSocket</artifactId>
<version>1.3.5</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>