读取高德室外天气工具类

  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 "";// 抛异常 返回空串
        }
    }
}

猜你喜欢

转载自blog.csdn.net/diyu122222/article/details/79019873