使用百度API的Sn签名方式获取天气情况

项目需求:

1:申请百度账号

2:成为开发者

3:获取服务AK和SK

工具类代码:

1:获取Sn

    public String caculateSn(Map paramsMap) throws UnsupportedEncodingException{
        SearchHttpSN snCal = new SearchHttpSN();
        String paramsStr = snCal.toQueryString(paramsMap);
       //对paramsStr前面拼接上/weather/v1/?(url地址的后缀)
        String wholeStr = new String("/weather/v1/?" + paramsStr + SK);
        // 对上面wholeStr再作utf8编码
        String tempStr = URLEncoder.encode(wholeStr, "UTF-8");

        // 调用下面的MD5方法得到最后的sn签名
        String sn = snCal.MD5(tempStr);
        return sn;
    }

    private String toQueryString(Map<?, ?> data)
            throws UnsupportedEncodingException {
        StringBuffer queryString = new StringBuffer();
        for (Map.Entry<?, ?> pair : data.entrySet()) {
            queryString.append(pair.getKey() + "=");
 
            queryString.append(UriUtils.encode((String) pair.getValue(), "UTF-8") + "&");
        }
        if (queryString.length() > 0) {
            queryString.deleteCharAt(queryString.length() - 1);
        }
        return queryString.toString();
    }

    // 来自stackoverflow的MD5计算方法,调用了MessageDigest库函数,并把byte数组结果转换成16进制
    private String MD5(String md5) {
        try {
            java.security.MessageDigest md = java.security.MessageDigest
                    .getInstance("MD5");
            byte[] array = md.digest(md5.getBytes());
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < array.length; ++i) {
                sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100)
                        .substring(1, 3));
            }
            return sb.toString();
        } catch (java.security.NoSuchAlgorithmException e) {
        }
        return null;
    }

2:调用API

    public void requestGetSN(String strUrl, Map<String, String> param) throws Exception {
        if (strUrl == null || strUrl.length() <= 0 || param == null || param.size() <= 0) {
            return;
        }

        StringBuffer queryString = new StringBuffer();
        queryString.append(strUrl);
        for (Map.Entry<?, ?> pair : param.entrySet()) {
            queryString.append(pair.getKey() + "=");
            queryString.append(UriUtils.encode((String) pair.getValue(), "UTF-8") + "&");
        }

        if (queryString.length() > 0) {
            queryString.deleteCharAt(queryString.length() - 1);
        }

        java.net.URL url = new URL(queryString.toString());
        System.out.println(queryString.toString());
        URLConnection httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.connect();

        InputStreamReader isr = new InputStreamReader(httpConnection.getInputStream());
        BufferedReader reader = new BufferedReader(isr);
        StringBuffer buffer = new StringBuffer();
        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        reader.close();
        isr.close();
    }

3.Test

public class SearchHttpSN {

    /**
     * 选择AK使用SN校验:
     */

    public static String AK = "AK";

    public static String SK = "SK";

    public static String URL = "https://api.map.baidu.com/weather/v1/?";

    public static void main(String[] args) throws Exception {

        SearchHttpSN snCal = new SearchHttpSN();

        Map params = new LinkedHashMap<String, String>();
        params.put("district_id", "320100");
        params.put("data_type", "all");
        params.put("ak", AK);

        params.put("sn", snCal.caculateSn(params));

        snCal.requestGetSN(URL, params);
    }
}

4.结果:

{
    "status": 0,
    "result": {
        "location": {
            "country": "中国",
            "province": "江苏省",
            "city": "南京市",
            "name": "南京",
            "id": "320100"
        },
        "now": {
            "text": "阴",
            "temp": 33,
            "feels_like": 35,
            "rh": 58,
            "wind_class": "2级",
            "wind_dir": "西南风",
            "uptime": "20240717153500"
        },
        "forecasts": [
            {
                "text_day": "阴",
                "text_night": "多云",
                "high": 34,
                "low": 28,
                "wc_day": "4~5级",
                "wd_day": "西南风",
                "wc_night": "4~5级",
                "wd_night": "西南风",
                "date": "2024-07-17",
                "week": "星期三"
            },
            {
                "text_day": "阴",
                "text_night": "多云",
                "high": 33,
                "low": 28,
                "wc_day": "4~5级",
                "wd_day": "西南风",
                "wc_night": "4~5级",
                "wd_night": "南风",
                "date": "2024-07-18",
                "week": "星期四"
            },
            {
                "text_day": "阴",
                "text_night": "多云",
                "high": 34,
                "low": 28,
                "wc_day": "4~5级",
                "wd_day": "西南风",
                "wc_night": "4~5级",
                "wd_night": "南风",
                "date": "2024-07-19",
                "week": "星期五"
            },
            {
                "text_day": "雷阵雨",
                "text_night": "阴",
                "high": 35,
                "low": 28,
                "wc_day": "4~5级",
                "wd_day": "西南风",
                "wc_night": "4~5级",
                "wd_night": "东南风",
                "date": "2024-07-20",
                "week": "星期六"
            },
            {
                "text_day": "多云",
                "text_night": "多云",
                "high": 36,
                "low": 27,
                "wc_day": "4~5级",
                "wd_day": "南风",
                "wc_night": "4~5级",
                "wd_night": "南风",
                "date": "2024-07-21",
                "week": "星期日"
            }
        ]
    },
    "message": "success"
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值