graduatedesign-Add the ability to get location information and weather forecasts to the app (JSON)

Source: Internet
Author: User

First, my app needs to get to the current location through the network. Here I found a JSON to get the local location information.

http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js    // get the city where the current network is located 

The information returned is:

var remote_ip_info = {"ret": 1, "Start":-1, "End":-1, "Country": "\u4e2d\u56fd", "Province": "\u6cb3\u5357", "City": "\ u6d1b\u9633 "," District ":" "," ISP ":" "," type ":" "," desc ":"};

The Chinese character coding in the return message is GBK, where we need to turn the code to get the location information directly.

Country is the country, province is the province, city is the town. Here I can get my current location information through the network.

On the Internet, check the weather forecast by querying the JSON on the server to get the weather information.

http://wthrcdn.etouch.cn/weatherapi?city= Beijing         // Get the weather situation in Beijing in recent days http:  //www.weather.com.cn/data/cityinfo/101010100.html  //101010100 weather ID in Beijing 

This is affixed with two URLs, the first return is in XML format and needs to be parsed by XML. The first one returns more information, but the second one seems to have a more complete message, but the link I've been through online has been a failure to return.

The first one has a drawback, is that there is no day of the weather (sunny, cloudy, rain, etc.), but for the forecast but there is.

The second temperature information is not accurate. Didn't figure out what was going on.

Getting JSON needs to pass the HTTP protocol, where I use the code: (Pass in the JSON address, return the string directly)

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 () {Httpurl                Connection Connection = null;  try {URL url = new URL (urlstring);                  Connection = (httpurlconnection) url.openconnection ();                    Connection.setrequestmethod ("GET");  Connection.setrequestproperty ("Charset", "UTF-8");                    Set the character set Connection.setconnecttimeout (8000);                    Connection.setreadtimeout (8000);                    int code = Connection.getresponsecode ();                        if (code = =) {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.appe                            nd (line + "/n"); }} catch (IoexCeption e) {e.printstacktrace ();                            } finally {try {outstream.close ();                            } catch (IOException e) {e.printstacktrace ();                        } outstring = Jsontext.tostring ();                    } log.i ("Infor", "Request succeeded" +filelength);                    } else {log.i ("Infor", "request Failed");                }} 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; }}

  

Here is the JSON that parses the weather information:

private void Analysisjsonweather (String jsonstring) {try {J            Sontokener 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 (); }    }

  

Finally, we enclose the code that parses the XML:

   XML file to get weather information over the network 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)//if followed by the text element, return its value {                                LOG.I ("Infor", "Get City weather error, the currently acquired city is:" + xmlcity);                            return false; }} else if (Name.equalsignorecase ("Wendu")) {Today.temper = INTEGER.PA                        Rseint (Pullparser.nexttext ()); } else if (Name.equalsignorecase ("Shidu")) {/* Delete non-numeric parts */String nu                            m = 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", "Wind Power:" + 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", "Get Current Position:" +STR); 

  

graduatedesign-Add the ability to get location information and weather forecasts to the app (JSON)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.