Android gets HTTP request JSON data

Source: Internet
Author: User

Package com.my.gethttpjsondata;

Import Java.io.BufferedReader;
Import Java.io.ByteArrayOutputStream;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
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.os.Bundle;
Import android.app.Activity;
Import Android.content.Context;
Import Android.util.Log;
Import Android.view.View;
Import Android.widget.TextView;
Import Android.widget.Toast;

public class Mainactivity extends Activity {

TextView TextView;

static String err;

@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);

TextView = (TextView) Findviewbyid (R.id.tv_json);

}

public void Click1 (view view)
{
Toast.maketext (Mainactivity.this, "start", 0). Show ();
String path= "Http://192.168.1.151:10080/?module={appid:%22d1%22,id:%22getalluser%22}";
try {
Textview.settext (getjsoncontent (path));
String r=getjsoncontent (path);
Toast.maketext (Mainactivity.this, R, 0). Show ();
Open a sub-thread for network operation, wait for return result, use handler to notify UI
New Thread (Networktask). Start ();

/**
List<map> list=new arraylist<map> ();
List=getjsonobject (Path,mainactivity.this);
for (Map list2:list) {
String id = list2.get ("UserID"). ToString ();
String name = List2.get ("UserName"). ToString ();
Toast.maketext (Mainactivity.this, "ID:" + id + "| Name: "+ Name, 0)." Show ();
}
**/

} catch (Exception e) {
Toast.maketext (Mainactivity.this, e.tostring (), 0). Show ();
E.printstacktrace ();
}

}

/**
* Network operation related sub-threads
*/
Runnable networktask = new Runnable () {

@Override
public void Run () {
String path= "Http://192.168.1.151:10080/?module={appid:%22d1%22,id:%22getalluser%22}";
List<map> list=new arraylist<map> ();
try {
List=getjsonobject (path);
} catch (Exception e) {

E.printstacktrace ();
}
for (Map list2:list) {
String id = list2.get ("UserID"). ToString ();
String name = List2.get ("UserName"). ToString ();
LOG.V ("Data", "ID:" + id + "| Name: "+ name");
}
}
};

public static list<map> Getjsonobject (String path) throws Exception {
list<map> list = new arraylist<map> ();
Map map = null;
URL url = new URL (path);
HttpURLConnection conn = (httpurlconnection) url.openconnection ();//using the HttpURLConnection object, we can get the Web page data from the network.
Conn.setconnecttimeout (5 * 1000); Unit is milliseconds, setting timeout is 5 seconds
Conn.setrequestmethod ("GET"); The httpurlconnection is requesting path paths through the HTTP protocol, so you need to set the request mode, not set because the default is get
LOG.V ("abc", "Status:" +conn.getresponsecode ());

if (conn.getresponsecode () = = 200) {//Determine if the request code is 200 yards, otherwise failed
InputStream is = Conn.getinputstream (); Get input stream
byte[] data = Readstream (IS); Convert input flow to character array
String json = new string (data); Converts a character array to a string


Data form: {"Total": 2, "Success": true, "Arraydata": [{"id": 1, "name": "Piglet"},{"id": 2, "name": "Kitten"}]}
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 ("total");
Boolean Success=jsonobject.getboolean ("Success");
LOG.I ("abc", "Total:" + All + "| Success: "+ success); Test data


Jsonarray Jsonarray = Jsonobject.getjsonarray ("data");//There is an array of data in it, you can get the array with Getjsonarray
for (int i = 0; i < jsonarray.length (); i++) {
Jsonobject item = jsonarray.getjsonobject (i); Get each object
int id = item.getint ("UserID"); Gets the value corresponding to the object
String name = item.getstring ("UserName");

Map = new HashMap (); Store in Map
Map.put ("UserID", id + "");
Map.put ("UserName", name);
List.add (map);
}
}

Test Data ******************

for (Map list2:list) {
String id = list2.get ("UserID"). ToString ();
String name = List2.get ("UserName"). ToString ();
LOG.V ("Data", "ID:" + id + "| Name: "+ name");
}

return list;
}


public 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 ();
}



public void Click2 (view view)
{
Thread Th=new Thread (new Runnable () {

@Override
public void Run () {
TODO auto-generated Method Stub
String Httpurl = "Http://apis.baidu.com/heweather/weather/free";
String Httparg = "city=beijing";
String Jsonresult = Request (Httpurl, httparg);
LOG.V ("Jsonresult", Jsonresult);
Toast.maketext (mainactivity.this, Jsonresult, 0). Show ();
}
});

Th.start ();

}

/**
* @param urlall
*: Request Interface
* @param httparg
*: Parameters
* @return Return results
*/
public static string request (String Httpurl, String httparg) {
BufferedReader reader = null;
String result = null;
StringBuffer SBF = new StringBuffer ();
Httpurl = Httpurl + "?" + Httparg;

try {
URL url = new URL (httpurl);
HttpURLConnection connection = (httpurlconnection) URL
. OpenConnection ();
Connection.setrequestmethod ("GET");
Fill in Apikey to HTTP header
Connection.setrequestproperty ("Apikey", "574cc9baa2b89769d89a6799c194f806");
Connection.connect ();
InputStream is = Connection.getinputstream ();
reader = new BufferedReader (new InputStreamReader (IS, "UTF-8"));
String strread = null;
while ((Strread = Reader.readline ()) = null) {
Sbf.append (Strread);
Sbf.append ("\ r \ n");
}
Reader.close ();
result = Sbf.tostring ();
} catch (Exception e) {
LOG.V ("Dituerr", e.tostring ());
E.printstacktrace ();

}
return result;
}

}

: Http://files.cnblogs.com/files/qujian15/GetHttpJsonData.rar

Android gets HTTP request JSON data

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.