Android obtains http request json data, androidjson

Source: Internet
Author: User

Android obtains http request json data, androidjson

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: % 22 getAllUser % 22 }";
Try {
// TextView. setText (getJsonContent (path ));
// String r = getJsonContent (path );
// Toast. makeText (MainActivity. this, r, 0). show ();
// Enable a sub-thread to perform network operations. Wait for a returned result and use handler to notify the 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 ();
}

}

/**
* Subthreads related to network operations
*/
Runnable networkTask = new Runnable (){

@ Override
Public void run (){
String path = "http: // 192.168.1.151: 10080 /? Module = {appId: % 22d1% 22, id: % 22 getAllUser % 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 (); // use the HttpURLConnection object to obtain webpage data from the network.
Conn. setConnectTimeout (5*1000); // The unit is milliseconds and the timeout value is set to 5 seconds.
Conn. setRequestMethod ("GET"); // HttpURLConnection requests the path through the HTTP protocol. Therefore, you need to set the request method. You can leave it unspecified because the default value is GET.
// Log. v ("abc", "Status:" + conn. getResponseCode ());

If (conn. getResponseCode () = 200) {// check whether the request code is 200; otherwise, the request fails.
InputStream is = conn. getInputStream (); // gets the input stream
Byte [] data = readStream (is); // converts the input stream to a character array
String json = new String (data); // converts a character array to a String


// Data format: {"total": 2, "success": true, "arrayData": [{"id": 1, "name": ""}, {"id": 2, "name": "kitten"}]}
JSONObject jsonObject = new JSONObject (json); // The returned data is of the Object type, so it can be directly converted into an Object.
// Int total = jsonObject. getInt ("total ");
Boolean success = jsonObject. getBoolean ("success ");
// Log. I ("abc", "total:" + total + "| success:" + success); // Test Data


JSONArray jsonArray = jsonObject. getJSONArray ("data"); // contains an array of data. You can use getJSONArray to obtain the array.
For (int I = 0; I <jsonArray. length (); I ++ ){
JSONObject item = jsonArray. getJSONObject (I); // obtain each object
Int id = item. getInt ("UserID"); // obtain the value of the object
String name = item. getString ("UserName ");

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

******************

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
*: Parameter
* @ Return result
*/
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 ");
// Enter 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

Related Article

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.