定位当前城市并获取天气信息

一、描述步骤

1.定位api:http://pv.sohu.com/cityjson?ie=utf-8
例子:var returnCitySN = {"cip": "113.66.222.99", "cid": "440100", "cname": "广东省广州市"};

2.获取天气api:(中央气象台接口)共3个步骤

步骤1:http://www.nmc.cn/rest/province (获取全国省份的代码)例如:广东省:AGD
步骤2:http://www.nmc.cn/rest/province/AGD (获取广东省的所有城市代码)例如:广州市:59287
步骤3:http://www.nmc.cn/rest/weather?stationid=59287(北京七天的白天和夜晚的天气信息)

3.参考资料
中英天气对照:https://wenku.baidu.com/view/2c211b48b52acfc788ebc92a.html
天气预报图例:http://www.weather.com.cn/static/html/legend.shtml

中央气象台的API获取天气:(缺点没有天气图标)
http://flash.weather.com.cn/wmaps/xml/china.xml
http://flash.weather.com.cn/wmaps/xml/beijing.xml

二、代码

1.保存天气信息类

public class WeatherForm {
    //天气描述
    private String weather;
    //图标
    private int img;
    //省
    private String provice;
    //城市
    private String city;
    //省市
    private String location;
    public WeatherForm(){
    }

    public WeatherForm(String weather,int img, String provice,
         String city, String location) {
        super();
        this.weather = weather;
        this.img = img;
        this.provice = provice;
        this.city = city;
        this.location = location;
    }
    public String getWeather() {
        return weather;
    }
    public void setWeather(String weather) {
        this.weather = weather;
    }
    public int getImg() {
        return img;
    }
    public void setImg(int img) {
        this.img = img;
    }
    public String getProvice() {
        return provice;
    }
    public void setProvice(String provice) {
        this.provice = provice;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    public String getLocation() {
        return location;
    }
    public void setLocation(String location) {
        this.location = location;
    }
    @Override
    public String toString() {
        return "WeatherForm [weather=" + weather
                + ", img=" + img
                + ", provice=" + provice + ", city=" + city
                + ", location=" + location
                +"]";
    }
}
2.调用中央气象台http接口,获取天气信息jons包,解析分解需要的信息

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.json.JSONObject;
import org.json.JSONException;
import org.json.JSONArray;
import android.util.Log;

public class WeatherQueryManage {
   private static String TAG = "WeatherQueryManage";
   public WeatherForm[] weatherquery() {
      WeatherForm[] WF = new WeatherForm[3];
      //http://m.weather.com.cn/data/101070101.html
      //String URL = "http://m.weather.com.cn/data/"+CityId+".html";
      //http://m.weather.com.cn/atad/101070101.html
      //String URL="http://www.weather.com.cn/weather/101070101.shtml";
      //String URL="http://m.weather.com.cn/atad/"+CityId+".html";
      //String URL="http://m.weather.com.cn/atad/101070101.html";
      //String URL="http://www.weather.com.cn/data/cityinfo/101010100.html";
      //String URL_img3 = "http://image.nmc.cn/assets/img/w/40x40/4/3.png";
      //String URL_img_url = "http://image.nmc.cn/assets/img/w/40x40/4/";
      //String URL_img_png = ".png"; String URL = "http://www.nmc.cn/rest/weather?stationid=54511";
      String URL2 = "http://flash.weather.com.cn/wmaps/xml/beijing.xml";
      String URL3 = "http://flash.weather.com.cn/wmaps/xml/china.xml";
      String URL_weather = "http://www.nmc.cn/rest/weather?stationid=";
      String URL_location = "http://pv.sohu.com/cityjson?ie=utf-8";
      String Weather_Result="";
      String Location_Result="";
      String city_code = "";
      String location = "";
      WeatherForm weaf = new WeatherForm();
      WF[0]=weaf;
      location = getLocation(WF);
      Log.v(TAG," test 121212");
      city_code = getCitycode(location,WF);
      if(city_code == null || "".equals(city_code)){
         Log.v(TAG," test city_code = "+city_code);
         return null;
      }
      HttpGet httpRequest = new HttpGet(URL_weather+city_code);
      //HttpGet httpRequest_location = new HttpGet(URL_location);
      Log.v("  test"," URL_weather+city_code:"+URL_weather+city_code);
      //Log.v("  test"," URL_location:"+URL_location);
      // 获得HttpResponse对象
      try {
         Log.v("  test"," HttpClient 1111111111111111:");
         HttpClient httpClient = new DefaultHttpClient();
         Log.v("  test"," HttpResponse 222222222222222");
         HttpResponse httpResponse = httpClient.execute(httpRequest);
         Log.v("  test"," HttpResponse 222222222222222"+httpResponse);
         if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            // 取得返回的数据
            Log.v("  test"," httpResponse.getStatusLine().getStatusCode():"+httpResponse.getStatusLine().getStatusCode());
            Weather_Result = EntityUtils.toString(httpResponse.getEntity());
            //Log.v("  test"," Weather_Result:"+Weather_Result);
         }
         //HttpClient httpClient_location = new DefaultHttpClient();
         //HttpResponse httpResponse_location = httpClient_location.execute(httpRequest_location);
         //if (httpResponse_location.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            // 取得返回的数据
         // Log.v("  test"," httpResponse_location.getStatusLine().getStatusCode():"+httpResponse_location.getStatusLine().getStatusCode());
         // Location_Result = EntityUtils.toString(httpResponse_location.getEntity());
         // Log.v("  test"," Location_Result:"+Location_Result);
         //}
      } catch (Exception e) {
         Log.v("  test  err  ++++++",""+e);
         WF[0] = new WeatherForm();
         WF[1] = new WeatherForm();
         WF[2] = new WeatherForm();
         return null;
      }

      //以下是对返回JSON数据的解析
      if( null!=Weather_Result  && !"".equals(Weather_Result)){
         try {
            //Log.v("  test "," 00000 "+Location_Result);
            JSONObject JO = new JSONObject(Weather_Result).getJSONObject("data");
            //int index = Location_Result.indexOf("{");
            //String city = new JSONObject(Location_Result.substring(index)).getString("cname");
            //Log.v("  test "," 111111 "+city);
                  //
            //Log.v("  test"," Weather__000"+JO.getString("real"));
            JSONArray jsonArray =new JSONArray(JO.getJSONObject("predict").getString("detail"));
            for(int i=0;i<jsonArray.length();i++){
               //Log.v("  test"," Weather__11"+i+jsonArray.getJSONObject(i));
            }
            //Log.v("  test"," Weather__222"+jsonArray.getJSONObject(0).getString("day"));

            Log.v("  test"," Weather__iiii"+jsonArray.getJSONObject(0));
            String day_weather = jsonArray.getJSONObject(0).getJSONObject("day").getJSONObject("weather").getString("info");
            String night_weather = jsonArray.getJSONObject(0).getJSONObject("night").getJSONObject("weather").getString("info");
            int img_day =  Integer.parseInt(jsonArray.getJSONObject(0).getJSONObject("day").getJSONObject("weather").getString("img"));
            int img_night =  Integer.parseInt(jsonArray.getJSONObject(0).getJSONObject("night").getJSONObject("weather").getString("img"));
            Log.v("  test"," day_weather="+day_weather);
            Log.v("  test"," night_weather="+night_weather);
            //Log.v("  test"," city=" +city);
            Log.v("  test"," img_day=" +img_day+" img_night="+img_night);
            Log.v("  test"," d&n "+day_weather.contains("9")+night_weather.contains("9"));
            //weaf.setCity(city);
               //weaf.setDdate(JO.getString("date_y"));
               //weaf.setWeek(JO.getString("week"));
               //weaf.setTemp(JO.getString("temp"));
               //weaf.setWind(JO.getString("wind"));
            if( !day_weather.contains("9")  && !night_weather.contains("9")  ) {
               if(day_weather.equals(night_weather))
                  WF[0].setWeather(day_weather);
               else
                  WF[0].setWeather(day_weather + "转" + night_weather);
               WF[0].setImg(img_day);
            }
            else if( day_weather.contains("9")  && !night_weather.contains("9") ){
               WF[0].setWeather(night_weather);
               WF[0].setImg(img_night);
            }
            else if( !day_weather.contains("9")  && night_weather.contains("9")  ){
               WF[0].setWeather(day_weather);
               WF[0].setImg(img_day);
            }
            else {
               Log.v("  test" ,"dayweather:"+day_weather+" nightweather"+night_weather);
               WF[0].setWeather("");
               WF[0].setImg(99);
            }
            //Log.v("  test"," WF[0]:"+WF[0]);

         } catch (JSONException e) {
            WF[0] = new WeatherForm();
            WF[1] = new WeatherForm();
            WF[2] = new WeatherForm();
            return null;
         }
      }
      Log.v("  test"," WF[0]:"+WF[0]);
      return WF;
   }

   private String getLocation(WeatherForm[] WF){
      String URL_location = "http://pv.sohu.com/cityjson?ie=utf-8";
      String location = "";
      String Location_Result="";
      HttpGet httpRequest_location = new HttpGet(URL_location);
      Log.v("  test"," URL_location:"+URL_location);
      // 获得HttpResponse对象
      try {
         HttpClient httpClient_location = new DefaultHttpClient();
         HttpResponse httpResponse_location = httpClient_location.execute(httpRequest_location);
         if (httpResponse_location.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            // 取得返回的数据
            Log.v("  test"," httpResponse_location.getStatusLine().getStatusCode():"+httpResponse_location.getStatusLine().getStatusCode());
            Location_Result = EntityUtils.toString(httpResponse_location.getEntity());
            //Log.v("  test"," Location_Result:"+Location_Result);
         }
      } catch (Exception e) {
         Log.v("  test getLocation err  ++++++",""+e);
         return null;
      }
      //以下是对返回JSON数据的解析
      if( null!=Location_Result  && !"".equals(Location_Result)){
         try {
            //Log.v("  test "," 00000 "+Location_Result);
            int index = Location_Result.indexOf("{");
            location = new JSONObject(Location_Result.substring(index)).getString("cname");
            Log.v("  test"," location=" +location);
            WF[0].setLocation(location);
         } catch (JSONException e) {
            Log.v("  test"," getLocation: err "+e);
            return null;
         }
      }
      Log.v("  test"," getLocation() done ==="+location);
      return location;
   }

   private String getCitycode(String location,WeatherForm[] WF)
   {
      Log.v("  test"," getCitycode=====");
      if(null == location || "".equals(location)){
         Log.v("  test"," location is null " +location);
         return null;
      }
      String URL_province = "http://www.nmc.cn/rest/province";
      String URL_city = "http://www.nmc.cn/rest/province/";
      String provice_Result = "";
      String provice_code = "";
      String provice_name = "";
      String city_Result = "";
      String city_code = "";
      String city_name = "";
      HttpGet httpRequest = new HttpGet(URL_province);
      Log.v(" test"," URL_province:"+URL_province);
      // 获得HttpResponse对象
      try {
         HttpClient httpClient = new DefaultHttpClient();
         HttpResponse httpResponse = httpClient.execute(httpRequest);
         if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            // 取得返回的数据
            Log.v(" test"," httpResponse.getStatusLine().getStatusCode():"+httpResponse.getStatusLine().getStatusCode());
            provice_Result = EntityUtils.toString(httpResponse.getEntity());
            //Log.v(" test"," provice_Result:"+provice_Result);
         }
      } catch (Exception e) {
         Log.v(" test provice_Result err  ++++++",""+e);
         return null;
      }
      //以下是对返回JSON数据的解析
      if( null!=provice_Result  && !"".equals(provice_Result)){
         try {
            JSONArray jsonArray =new JSONArray(provice_Result);
            for(int i=0;i<jsonArray.length();i++){
               //Log.v(" test"," provice__11"+i+jsonArray.getJSONObject(i));
               if(location.contains(jsonArray.getJSONObject(i).getString("name"))){
                  provice_name = jsonArray.getJSONObject(i).getString("name");
                  Log.v(" test"," provice_name="+provice_name);
                  provice_code = jsonArray.getJSONObject(i).getString("code");
                  Log.v(" test"," provice_code="+provice_code);
                  WF[0].setProvice(provice_name);
                  break;
               }
            }
         } catch (JSONException e) {
            Log.v(" test"," get provice_code err:");
            return null;
         }
      }
      if( null!=provice_code && !"".equals(provice_code) ){
         HttpGet httpRequest_city = new HttpGet(URL_city+provice_code);
         Log.v(" test"," URL_city+provice_code:"+URL_city+provice_code);
         // 获得HttpResponse对象
         try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpResponse httpResponse = httpClient.execute(httpRequest_city);
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
               // 取得返回的数据
               Log.v(" test"," httpResponse.getStatusLine().getStatusCode():"+httpResponse.getStatusLine().getStatusCode());
               city_Result = EntityUtils.toString(httpResponse.getEntity());
               //Log.v(" test"," city_Result:"+city_Result);
            }
         } catch (Exception e) {
            Log.v(" test get city_Result err  ++++++",""+e);
            return null;
         }
         //以下是对返回JSON数据的解析
         if( null!=city_Result  && !"".equals(city_Result)){
            try {
               JSONArray jsonArray =new JSONArray(city_Result);
               for(int i=0;i<jsonArray.length();i++){
                  //Log.v(" test"," city__11"+i+jsonArray.getJSONObject(i));
                  if(location.contains(jsonArray.getJSONObject(i).getString("city"))){
                     city_name = jsonArray.getJSONObject(i).getString("city");
                     Log.v(" test"," city_name="+city_name);
                     city_code = jsonArray.getJSONObject(i).getString("code");
                     Log.v(" test"," city_code="+city_code);
                     WF[0].setCity(city_name);
                     break;
                  }
               }
            } catch (JSONException e) {
               Log.v(" test"," get provice_code err:");
               return null;
            }
         }
      }
      return city_code;
   }
   /**
    * [{"code":"ABJ","name":"北京市","url":"/publish/forecast/ABJ.html"},
    * {"code":"ATJ","name":"天津市","url":"/publish/forecast/ATJ.html"},
    * {"code":"AHE","name":"河北省","url":"/publish/forecast/AHE.html"},
    * {"code":"ASX","name":"山西省","url":"/publish/forecast/ASX.html"},
    * {"code":"ANM","name":"内蒙古自治区","url":"/publish/forecast/ANM.html"},
    * {"code":"ALN","name":"辽宁省","url":"/publish/forecast/ALN.html"},
    * {"code":"AJL","name":"吉林省","url":"/publish/forecast/AJL.html"},
    * {"code":"AHL","name":"黑龙江省","url":"/publish/forecast/AHL.html"},
    * {"code":"ASH","name":"上海市","url":"/publish/forecast/ASH.html"},
    * {"code":"AJS","name":"江苏省","url":"/publish/forecast/AJS.html"},
    * {"code":"AZJ","name":"浙江省","url":"/publish/forecast/AZJ.html"},
    * {"code":"AAH","name":"安徽省","url":"/publish/forecast/AAH.html"},
    * {"code":"AFJ","name":"福建省","url":"/publish/forecast/AFJ.html"},
    * {"code":"AJX","name":"江西省","url":"/publish/forecast/AJX.html"},
    * {"code":"ASD","name":"山东省","url":"/publish/forecast/ASD.html"},
    * {"code":"AHA","name":"河南省","url":"/publish/forecast/AHA.html"},
    * {"code":"AHB","name":"湖北省","url":"/publish/forecast/AHB.html"},
    * {"code":"AHN","name":"湖南省","url":"/publish/forecast/AHN.html"},
    * {"code":"AGD","name":"广东省","url":"/publish/forecast/AGD.html"},
    * {"code":"AGX","name":"广西壮族自治区","url":"/publish/forecast/AGX.html"},
    * {"code":"AHI","name":"海南省","url":"/publish/forecast/AHI.html"},
    * {"code":"ACQ","name":"重庆市","url":"/publish/forecast/ACQ.html"},
    * {"code":"ASC","name":"四川省","url":"/publish/forecast/ASC.html"},
    * {"code":"AGZ","name":"贵州省","url":"/publish/forecast/AGZ.html"},
    * {"code":"AYN","name":"云南省","url":"/publish/forecast/AYN.html"},
    * {"code":"AXZ","name":"西藏自治区","url":"/publish/forecast/AXZ.html"},
    * {"code":"ASN","name":"陕西省","url":"/publish/forecast/ASN.html"},
    * {"code":"AGS","name":"甘肃省","url":"/publish/forecast/AGS.html"},
    * {"code":"AQH","name":"青海省","url":"/publish/forecast/AQH.html"},
    * {"code":"ANX","name":"宁夏回族自治区","url":"/publish/forecast/ANX.html"},
    * {"code":"AXJ","name":"新疆维吾尔自治区","url":"/publish/forecast/AXJ.html"},
    * {"code":"AXG","name":"香港特别行政区","url":"/publish/forecast/AXG.html"},
    * {"code":"AAM","name":"澳门特别行政区","url":"/publish/forecast/AAM.html"},
    * {"code":"ATW","name":"台湾省","url":"/publish/forecast/ATW.html"}]
    *
    *
    * [{"code":"54511","province":"北京市","city":"北京","url":"/publish/forecast/ABJ/beijing.html"},
    * {"code":"54499","province":"北京市","city":"昌平","url":"/publish/forecast/ABJ/changping.html"},
    * {"code":"54433","province":"北京市","city":"朝阳","url":"/publish/forecast/ABJ/chaoyang.html"},
    * {"code":"54594","province":"北京市","city":"大兴","url":"/publish/forecast/ABJ/daxing.html"},
    * {"code":"54596","province":"北京市","city":"房山","url":"/publish/forecast/ABJ/fangshan.html"},
    * {"code":"54514","province":"北京市","city":"丰台","url":"/publish/forecast/ABJ/fengtai.html"},
    * {"code":"54399","province":"北京市","city":"海淀","url":"/publish/forecast/ABJ/haidian.html"},
    * {"code":"54419","province":"北京市","city":"怀柔","url":"/publish/forecast/ABJ/huairou.html"},
    * {"code":"54505","province":"北京市","city":"门头沟","url":"/publish/forecast/ABJ/mentougou.html"},
    * {"code":"54416","province":"北京市","city":"密云","url":"/publish/forecast/ABJ/miyun.html"},
    * {"code":"54424","province":"北京市","city":"平谷","url":"/publish/forecast/ABJ/pinggu.html"},
    * {"code":"54513","province":"北京市","city":"石景山","url":"/publish/forecast/ABJ/shijingshan.html"},
    * {"code":"54398","province":"北京市","city":"顺义","url":"/publish/forecast/ABJ/shunyi.html"},
    * {"code":"54431","province":"北京市","city":"通州","url":"/publish/forecast/ABJ/tongzhou.html"},
    * {"code":"54406","province":"北京市","city":"延庆","url":"/publish/forecast/ABJ/yanqing.html"}]
    */
}


3.调用接口类获取天气

/**
 * 2021/7/9
 * 获取天气
*/
public void getweather()
{
        Log.v(TAG," test getweather");
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.v(TAG," test getweather run");
                //创建返回的天气信息对象,是一个对象数组,用来放3天的天气
                WeatherForm[] WF = new WeatherForm[3];
                //查询天气,返回3天的天气信息
                Log.v(TAG," test getweather::::");
                WeatherQueryManage WQM = new WeatherQueryManage();
                int count = 1;
                while(!haveInternet())
                {
                    Log.v(TAG," test count="+count);
                    if(count++>10) {
                        Log.v(TAG," test network disconnect!");
                        return;
                    }
                    try{
                        Thread.sleep(100);
                    }catch(Exception e){
                        Log.e(TAG," test sleep err! "+e);
                    }
                }
                Log.v(TAG," test haveInternet!");
                WF = WQM.weatherquery();
                if(null!=WF && WF.length>=1){
                    Log.v(TAG," test getweather: WF.length="+WF.length);
                    Log.v(TAG," test weather:"+WF[0].getWeather());
                    String weather = WF[0].getWeather();
                    Log.v(TAG," test weather send :"+weather);
                    Message message = new Message();
                    message.what = 99;
                    message.obj = WF[0].getWeather();
                    message.arg1 = WF[0].getImg();
                    Handler.sendMessage(message);
                }
            }
        }).start();
}


参考路径:
获取当前城市:https://blog.csdn.net/Frederick_Fung/article/details/107718091?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522162583091916780366597455%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=162583091916780366597455&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~first_rank_v2~rank_v29-27-107718091.pc_search_result_before_js&utm_term=%E7%AE%80%E5%8D%95%E8%8E%B7%E5%8F%96%E5%BD%93%E5%89%8D%E5%9F%8E%E5%B8%82%E6%8E%A5%E5%8F%A3%E5%85%8D%E8%B4%B9&spm=1018.2226.3001.4187

获取天气详细步骤:(中央气象台api)https://blog.csdn.net/u014436243/article/details/113625266?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522162581684716780261942329%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=162581684716780261942329&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~first_rank_v2~rank_v29-4-113625266.pc_search_result_before_js&utm_term=%E8%8E%B7%E5%8F%96%E5%BC%80%E6%BA%90%E5%A4%A9%E6%B0%94%E4%BF%A1%E6%81%AF&spm=1018.2226.3001.4187

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值