java+高德天气api调用(加数字签名)

1.前提

登录高德天气官网,进入控制台之后创建web服务的应用
在这里插入图片描述
完成之后进入设置勾选数字签名权限,就得到了key和秘钥
在这里插入图片描述

2.实例代码

参数:
city 所在城市的adcode
用户key
sig 签名

@Repository
public class Weather {
     // key
    @Value("${map.key}")
    public String key;

    // 数字签名秘钥
    @Value("${map.sig}")
    public String sig;

    @Autowired
    private urlUtil urlUtil;

    @Autowired
    public md5Util md5Util;
    public String getWeather() {
        try {
            String str = "https://restapi.amap.com/v3/weather/weatherInfo?";
            // 请求参数(需排序
            String param = "city="+310110+"&key="+key;
            // md5加密得到签名(参数和秘钥)
            String md5 =md5Util.getMD5(param+sig);
            System.out.println(md5);

            URL url = new URL(str+param+"&sig="+md5);
            System.out.println(url);
            HttpURLConnection conn = urlUtil.getConn(url);
            conn.setRequestMethod("GET");

            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            StringBuilder result = null;
            while ((line = br.readLine())!= null){
                System.out.println(line);
                return line;
        }

            return  result.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

工具代码:

@Component
public class md5Util {
    // md5加密
    public  String getMD5(String sign){
        return DigestUtils.md5DigestAsHex(sign.getBytes());
    }
}
@Component
public class urlUtil {
    public HttpURLConnection getConn(URL  url){
        try {
				// 访问url
            return  (HttpURLConnection)url.openConnection();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}

3.结果

在这里插入图片描述
4.注意
加了数字签名麻烦一丢丢
md5加密参数需要按字典顺序排序然后将私钥加后面,直接拼接后面
请求报文需要高德需要的报文以及sig报文

URL url = new URL(str+param+"&sig="+md5);

注意事项见文档
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要在Java调用高德地图API,你可以按照以下步骤进行操作: 1. 创建一个工具类MapUtil,并导入所需的包,例如net.sf.json、org.apache.commons.collections等。 2. 在工具类中定义你在高德官网获取的key,例如private static String key = "xxxxxxxxxxxxxxxxxxxxxxxxx"; 3. 在工具类中编写方法来调用高德地图API。你可以使用Java的URL和HttpURLConnection类来发送HTTP请求,并通过API的URL和参数生成请求URL。 4. 发送HTTP请求并获取响应。可以使用URLConnection的getInputStream()方法来获取API的响应数据。 5. 解析API的响应数据。根据API文档中的返回数据格式,你可以使用JSON库解析响应数据,例如使用JSONObject和JSONArray类来解析JSON格式的数据。 6. 处理解析后的数据。你可以根据需要提取所需的信息,例如获取地理坐标、距离、路线等。 下面是一个示例代码来调用高德地图API: ```java import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.apache.commons.collections.MapUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.util.List; import java.util.Map; import java.util.regex.Pattern; public class MapUtil { private static final Logger LOGGER = LoggerFactory.getLogger(MapUtil.class); private static String key = "xxxxxxxxxxxxxxxxxxxxxxxxx"; public static String getResponse(String urlString) throws IOException { StringBuilder result = new StringBuilder(); URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = reader.readLine()) != null) { result.append(line); } reader.close(); connection.disconnect(); return result.toString(); } public static JSONObject getJson(String urlString) throws IOException { String response = getResponse(urlString); return JSONObject.fromObject(response); } public static void main(String[] args) { try { String apiUrl = "https://restapi.amap.com/v3/place/text?keywords=北京&key=" + key; JSONObject result = getJson(apiUrl); // 解析结果 JSONArray pois = result.getJSONArray("pois"); for (int i = 0; i < pois.size(); i++) { JSONObject poi = pois.getJSONObject(i); String name = poi.getString("name"); String location = poi.getString("location"); System.out.println(name + ": " + location); } } catch (IOException e) { LOGGER.error("Failed to call AMap API: " + e.getMessage()); } } } ``` 请注意,这只是一个示例代码,你可以根据具体需求进行修改和扩展。你可以根据高德地图API文档提供的接口和参数来调用不同的功能和服务。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [SpringCloud之如何在项目中调用高德地图API](https://blog.csdn.net/qq_31122833/article/details/80653419)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值