1. 程式人生 > >GraduateDesign-給APP添加獲取位置信息和天氣預報的功能(json)

GraduateDesign-給APP添加獲取位置信息和天氣預報的功能(json)

當前位置 失敗 rac reader adl country oca import 功能

首先,我的app需要通過網絡來獲取當前所在的位置。這裏我找到了一個json來獲取本地位置信息。

http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js    //獲得當前網絡所在城市

返回來的信息是:

var remote_ip_info = {"ret":1,"start":-1,"end":-1,"country":"\u4e2d\u56fd","province":"\u6cb3\u5357","city":"\u6d1b\u9633","district":"","isp":"","type":"","desc":""};

返回信息中的漢字編碼是gbk,這裏我們需要轉一下編碼就能直接拿到位置信息。

country 是 國家,province 是 省份,city 是所在的城市。這裏我就可以通過網絡來獲取我當前所在的位置信息。

在網上查了一下,查詢天氣預報都是通過查詢服務器上的json來獲取天氣信息。

http://wthrcdn.etouch.cn/WeatherApi?city=北京        //獲得北京近幾天的天氣情況

http://www.weather.com.cn/data/cityinfo/101010100.html  //101010100北京的氣象ID

這是貼除了兩個網址,第一個返回是xml格式,需要通過xml解析。第一個返回的信息較全,但是第二個好像也有較全的信息,但是我通過網上的鏈接一直是返回失敗。

第一個有一個缺點,就是沒有當天的天氣狀態(晴、多雲、雨等),但是對預報來說卻有。

第二個溫度信息不怎麽準。沒有弄明白是怎麽回事。

獲取json需要通過http協議,這裏貼上我用到到的代碼:(傳入json地址,直接返回字符串)

package com.lmissw.mydesignedapp;

import com.lmissw.mydesignedapp.MainActivity;
import android.util.Log;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

/**
 * Created by ZhouWangsheng on 2018/1/9.
 */

public class httpGetString {

    private static String urlString = null;
    private static String httpUrl = null;

    private InputStream outStream = null;
    private static String outString = null;

    public static String getString( String urlStr )
    {
        if(urlStr==null)
            return null;
        urlString=urlStr;
        outString = null;
        Thread httpThread = new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                try {
                    URL url = new URL(urlString);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setRequestProperty("Charset", "UTF-8");  // 設置字符集
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    int code = connection.getResponseCode();

                    if (code == 200) {
                        InputStream outStream = connection.getInputStream();
                        int fileLength = connection.getContentLength();

                        BufferedReader reader = new BufferedReader(new InputStreamReader(outStream));
                        StringBuilder jsonText = new StringBuilder();
                        String line = null;
                        try {
                            while ((line = reader.readLine()) != null) {
                                jsonText.append(line + "/n");
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        } finally {
                            try {
                                outStream.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            outString = jsonText.toString();
                        }
                        Log.i("Infor", "請求成功 "+fileLength);
                    } else {
                        Log.i("Infor", "請求失敗");
                    }
                } catch (ProtocolException e) {
                    e.printStackTrace();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                        Log.i("Infor", "disconnect ok");
                    }
                }
            }
        });
        httpThread.start();
        while(httpThread.isAlive());
        Log.i("Infor", "httpData:"+outString);
        return outString;
    }
}

  

下面是解析天氣信息的json:

private void  analysisJsonWeather( String jsonString )
    {
        try {
            JSONTokener  jsonParser = new JSONTokener( jsonString );
            JSONObject json = (JSONObject)jsonParser.nextValue();

            JSONObject jsonWeather = json.getJSONObject("weatherinfo");
            String str = jsonWeather.getString("city");
            if(str.equals(localCity)==false)
            {
                return;
            }
            str = jsonWeather.getString("temp1");
          //  today.temperMin= Integer.parseInt(str.replaceAll("[^-+.\\d]", ""));
            str = jsonWeather.getString("temp2");
          //  today.temperMax= Integer.parseInt(str.replaceAll("[^-+.\\d]", ""));
          //  Log.i("Infor", "max min:"+today.temperMax+" "+today.temperMin);

            today.type = jsonWeather.getString("weather");
           // Log.i("Infor", "type:"+today.type);

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

  

最後附上解析xml的代碼:

   //通過網絡獲取天氣信息的xml文件
        String xmlText = httpGetString.getString(httpWeather+localCity);

        if(xmlText==null)
            return false;
        String str=" ";
        ByteArrayInputStream stream = new ByteArrayInputStream(xmlText.getBytes());
        try {
            XmlPullParserFactory pullFactory=XmlPullParserFactory.newInstance();
            XmlPullParser pullParser=pullFactory.newPullParser();
            pullParser.setInput(stream,"UTF-8");
            int entype=pullParser.getEventType();

            while (entype!=XmlPullParser.END_DOCUMENT) {
                String startTag=null;
                String textData=null;
                switch(entype) {
                    case XmlPullParser.START_DOCUMENT:   break;
                    case XmlPullParser.START_TAG:
                        String name = pullParser.getName();
                        if (name.equalsIgnoreCase("city")) {
                            String xmlCity = pullParser.nextText();
                            if (xmlCity.equalsIgnoreCase(localCity) == false)    // 如果後面是Text元素,即返回它的值
                            {
                                Log.i("Infor", "獲取城市天氣出錯,當前獲取的城市是:" + xmlCity);
                                return false;
                            }
                        } else if (name.equalsIgnoreCase("wendu")) {
                            today.temper = Integer.parseInt(pullParser.nextText());
                        } else if (name.equalsIgnoreCase("shidu")) {
                            /* 刪除非數字部分 */
                            String num = pullParser.nextText().replaceAll("[^-+.\\d]", "");
                            today.humidity = Integer.parseInt(num);


                        } else if (name.equalsIgnoreCase("fengxiang")) {
                            today.windDir = pullParser.nextText();
                        } else if (name.equalsIgnoreCase("updatetime")){
                            today.updateTime = pullParser.nextText();
                        }else if (name.equalsIgnoreCase("yesterday")) {

                            int begin = xmlText.toString().indexOf(‘!‘);
                            String fengliString = xmlText.substring(begin+6,begin+16);
                            begin = fengliString.toString().indexOf(‘[‘);
                            int end = fengliString.toString().indexOf(‘]‘);
                            today.windpower = fengliString.substring(begin+1,end);
                            Log.i("Infor", "風力:" + today.windpower);
                            return true;
                        }
                            break;
                    case XmlPullParser.END_DOCUMENT:    break;
                    case XmlPullParser.END_TAG:         pullParser.getName(); break;
                }
                entype=pullParser.next();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        Log.i("Infor", "獲得當前位置:"+str);

  

GraduateDesign-給APP添加獲取位置信息和天氣預報的功能(json)