读取高德室外天气工具类

  1. 导包

commons-beanutils.jar
commons-collections-3.1.jar
commons-lang-2.4.jar
ezmorph-1.0.6.jar
json-lib-2.4-jdk15.jar

  1. 工具类
package cn.qineng.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * @Author wy
 * @Date 2018年1月9日上午10:42:45
 * @Version 1.0
 */
public class WeatherUtils {
    public static void main(String[] args) {
        String outRoomTemperature = getOutRoomTemperatureByGaoDe("汕尾");
        System.out.println(outRoomTemperature);
    }

    /**
     * 高德获取天气信息
     * 
     * @param cityName
     * @return
     */
    public static String getOutRoomTemperatureByGaoDe(String cityName) {
        // 读取 高德天气
        StringBuffer strBuf = new StringBuffer();
        try {
            cityName = URLEncoder.encode(cityName, "utf-8");
            String accesskey = "sdfsdfsdfsdfsdfsdfsdf"; // 密匙
            String url = "http://restapi.amap.com/v3/weather/weatherInfo?key="
                    + accesskey + "&city=" + cityName + "&extensions=base";
            URL u = new URL(url);
            URLConnection con = u.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    con.getInputStream(), "utf-8"));
            String line = null;
            while ((line = in.readLine()) != null) {
                strBuf.append(line);
            }
            in.close();
            // 获取 高德天气
            String outRoomWeaterJson = strBuf.toString();
            // 使用json 解析
            JSONObject weathJsonObj = JSONObject.fromObject(outRoomWeaterJson);
            JSONArray lives = weathJsonObj.getJSONArray("lives");
            // 天气信息状态为1 , 返回室外天气
            if (weathJsonObj.get("status").toString().equals("1")) {
                return (String) lives.getJSONObject(0).get("temperature");
            } else {
                return ""; // 否则返回 空串
            }
        } catch (Exception e) {
            return "";// 抛异常 返回空串
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值