package com.hhx.controller;标签:java,String,经纬度,new,地址,location,org,import,定时 From: https://www.cnblogs.com/hhx070911/p/17797115.html
import com.hhx.bean.Files;
import com.hhx.dao.FilesDao;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
/**
* 定时
*/
@Component
@EnableScheduling
public class MyScheduledTasks {
@Resource
FilesDao fd;
@Scheduled(fixedDelay = 60000) // 每隔一分钟执行一次
public void myTask() {
// 定时任务执行的逻辑
List<Files> files = fd.selByNull();
for (int i = 0; i < files.size(); i++) {
try {
// 输入地名
String address = files.get(i).getField0001();
// 构建请求URL
String urlStr = "https://restapi.amap.com/v3/geocode/geo?address=" + URLEncoder.encode(address, "UTF-8") + "&output=json&key=e842114cf69ccfae6edc402e1ef2a799";
// 发送HTTP请求
URL url = new URL(urlStr);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
// 读取响应内容
StringBuilder response = new StringBuilder();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
response.append(line);
}
in.close();
}
// 解析JSON响应
JSONObject jsonObject = new JSONObject(response.toString());
JSONArray geocodes = jsonObject.getJSONArray("geocodes");
if (geocodes.length() > 0) {
JSONObject location = geocodes.getJSONObject(0);
String latitude = location.getString("location").split(",")[1];
String longitude = location.getString("location").split(",")[0];
System.out.println("经度: " + longitude);
System.out.println("纬度: " + latitude);
fd.upByField0001(address, longitude, latitude);
} else {
System.out.println("未找到该地点的经纬度信息");
}
} catch (IOException | JSONException e) {
e.printStackTrace();
}
}
}
}