定时获取地址经纬度信息

package com.hhx.controller;

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();
}
}

}

}
posted @   霍叔  阅读(42)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗
点击右上角即可分享
微信分享提示