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

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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值