Android acquires JSON and UI updates via HttpURLConnection

Source: Internet
Author: User

This example uses the combination of Httpurlconnection+thread+handler to get the JSON data through HttpURLConnection in the new Thread and to update the UI interface in handler.






You can also use httpclient, asynctask to achieve this function, do not say here.


It's not a lot of nonsense, directly on the code.






-------------------------------Split Line----------------------------------------


Activity_main.xml (only a simple textview for displaying the JSON after retrieving its text)




<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android"      xmlns:tools= "http// Schemas.android.com/tools "      android:id=" @+id/container "      android:layout_width=" Match_parent "      Android : layout_height= "match_parent"      tools:context= "Com.zb.json_text. Mainactivity "      tools:ignore=" Mergerootframe "      android:background=" #f1f1f1 "      android:orientation=" Vertical ">        <textview           android:id=" @+id/textview_01 "          android:layout_width=" Match_parent "          android:layout_height= "wrap_content"          android:text= "go, always arrive ..."/>           




Mainactivity.java




Package com.zb.json_text;  Import Java.io.ByteArrayOutputStream;  Import Java.io.InputStream;  Import java.net.HttpURLConnection;  Import Java.net.URL;  Import java.util.ArrayList;  Import Java.util.HashMap;  Import java.util.List;      Import Java.util.Map;  Import Org.json.JSONArray;    Import Org.json.JSONObject;  Import android.app.Activity;  Import Android.os.Bundle;  Import Android.os.Handler;    Import Android.widget.TextView;      public class Mainactivity extends Activity {private TextView textview_01;        Private list<map<string, string>> slist;  Private Handler Handler = new Handler () {public void Handlemessage (android.os.Message msg) {switch (msg.what) {case 0:map<string, string> Map = Slist.get (2);//example, get the value of subscript 2 directly, you can                The loop takes the value of the list out of Textview_01.settext (Map.get ("title"));//Updates UI break in handler;              Default:break;}          }      };          @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);            Setcontentview (R.layout.activity_main);          Final String Path = "Http://m.lalas.cn/help/all_1.html?format=json&size=5";            textview_01 = (TextView) Findviewbyid (r.id.textview_01); New Thread () {//Create child thread for network access operation public void Run () {try {slist = Getjso                      Nobject (path);                  Handler.sendemptymessage (0);                  } catch (Exception e) {e.printstacktrace ();      }}}.start (); /** * Get JSON data on the network * @param path * @return * @throws Exception */Public Stati C list<map<string, string>> getjsonobject (String path) throws Exception {list<map& Lt String, string>> list = new arraylist<map<string, StriNg>> ();          map<string, string> map = null;          URL url = new URL (path);          Using the HttpURLConnection object, we can get the webpage data from the webpage httpurlconnection conn = (httpurlconnection) url.openconnection ();          The unit is in milliseconds and the timeout is set to 5 seconds conn.setconnecttimeout (15 * 1000);          The HttpURLConnection object is requested through the HTTP protocol, so you need to set the request mode, not set, because the default is get Conn.setrequestmethod ("get");              if (conn.getresponsecode () = = 200) {//To determine if the request code is 200, otherwise fails inputstream is = Conn.getinputstream ();//Get input stream byte[] data = Readstream (IS); Convert the input stream into a string group of strings JSON = new string (data);              Convert string Group to string//data form: {"Total": 2, "Success": true, "Arraydata": [{"id": 1, "name": "Zhang San"},{"id": 2, "name": "Reese"}]} Jsonobject jsonobject = new Jsonobject (JSON);              The returned data form is an object type, so it can be converted directly to an object int total = Jsonobject.getint ("Count");                String keywords = jsonobject.getstring ("keywords"); There's an array inside.Data, you can use Getjsonarray to get the array jsonarray Jsonarray = Jsonobject.getjsonarray ("Data");                   for (int i = 1; i < jsonarray.length (); i++) {Jsonobject item = jsonarray.getjsonobject (i);//Get each object                  int id = item.getint ("id");                  String title = item.getstring ("title");                  String Description = item.getstring ("description");                  int time = Item.getint ("Time");                  Map = new hashmap<string, string> ();                  Map.put ("id", ID + "");                  Map.put ("title", title);                  Map.put ("description", description);                  Map.put ("Time", Time + "");              List.add (map);      }} return list; } private static byte[] Readstream (InputStream inputstream) throws Exception {Bytearrayoutputstream bout          = new Bytearrayoutputstream ();          byte[] buffer = new byte[1024];         int len = 0; while (len = inputstream.read (buffer))! =-1) {bout.write (buffer, 0, Len);          } bout.close ();          Inputstream.close ();      return Bout.tobytearray ();   }    }





Source Address: http://download.csdn.net/detail/u011732740/8854953

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android acquires JSON and UI updates via HttpURLConnection

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.