Java代码如何结合高德地图API实现实时公交到站信息查询

2024年12月24日 建站教程

利用高德地图API查询实时公交到站信息,Java代码示例如下:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
 
public class BusQuery {
  public static void main(String[] args) {
    try {
      // 准备查询的URL
      String key = "你的密钥";
      String city = "北京";
      String keywords = "天安门";
      String url = "https://restapi.amap.com/v3/bus/stopname?key=" + key + "&city=" + city + "&keywords=" + keywords;
       
      // 发送查询请求
      HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
      connection.setRequestMethod("GET");
      connection.setConnectTimeout(5000);
       
      // 获取查询结果
      int responseCode = connection.getResponseCode();
      if(responseCode == 200) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        StringBuilder response = new StringBuilder();
        while ((line = reader.readLine()) != null) {
          response.append(line);
        }
        reader.close();
         
        // 输出查询结果
        System.out.println(response.toString());
      } else {
        System.out.println("查询失败");
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

本文链接:http://so.lmcjl.com/news/20053/

展开阅读全文
相关内容