# 根据经纬度获取天气信息

根据经纬度获取天气信息

可用的接口:

http://m.weather.com.cn/d/town/index?lat=31.97958&lon=120.89371
http://m.weather.com.cn/d/town/today?lat=31.97958&lon=120.89371

    public static String getToday(String log, String lat ){
   
        //lat 小  log  大
        //参数解释: 纬度,经度 type 001 (100代表道路,010代表POI,001代表门址,111可以同时显示前三项)
        String urlString = "http://m.weather.com.cn/d/town/today?lat="+lat +"&" +"lon=" +log;
        try {
   
            URL url = new URL(urlString);
            java.net.HttpURLConnection conn = (java.net.HttpURLConnection)url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("GET");
            //获取输入流

            java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(conn.getInputStream(),"UTF-8"));
            String line ;
            StringBuffer buffer = new StringBuffer();
            while ((line = in.readLine()) != null) {
   
                buffer.append(line);
            }
            in.
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要根据经纬度获取天气,可以使用第三方天气 API。以下是一种使用 OpenWeatherMap API 获取天气数据的示例: ```java import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import org.json.JSONObject; public class Weather { public static void main(String[] args) { try { // 经纬度信息 double lat = 40.7128; double lon = -74.0060; // 调用 OpenWeatherMap API String apiKey = "your_api_key"; String url = "https://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon + "&appid=" + apiKey; URLConnection conn = new URL(url).openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line); } reader.close(); // 解析 JSON 数据 JSONObject json = new JSONObject(sb.toString()); JSONObject main = json.getJSONObject("main"); double temp = main.getDouble("temp"); double feelsLike = main.getDouble("feels_like"); double humidity = main.getDouble("humidity"); String description = json.getJSONArray("weather").getJSONObject(0).getString("description"); // 打印天气信息 System.out.println("Temperature: " + temp + " K"); System.out.println("Feels like: " + feelsLike + " K"); System.out.println("Humidity: " + humidity + " %"); System.out.println("Description: " + description); } catch (Exception e) { e.printStackTrace(); } } } ``` 需要替换代码中的 `your_api_key` 为你自己的 OpenWeatherMap API Key。此示例仅提供了温度、体感温度、湿度和天气描述等基本信息,你可以根据需要选择解析更多的 JSON 数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值