GraduateDesign-給APP添加擷取位置資訊和天氣預報的功能(json)

來源:互聯網
上載者:User

標籤:功能   tor   tag   analysis   replace   touch   desc   oca   擷取位置   

首先,我的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)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.