Android: getting data from the Internet (images, webpages, xml, json, etc)

Source: Internet
Author: User

1> get data from the Network (images, webpages, xml, json, etc)
 
A. Obtain an image from the Internet and display it on your mobile phone.
This is in java

Public class ImageRequest {

/**
* @ Param args
*/
Public static void main (String [] args) throws Exception {
URL url = new URL ("http://www.bkjia.com/uploadfile/2012/0419/20120419023209724.jpg ");
HttpURLConnection conn = (HttpURLConnection) url. openConnection ();
Conn. setRequestMethod ("GET ");
Conn. setConnectTimeout (5*1000 );
InputStream inStream = conn. getInputStream (); // obtain image data through the input stream
Byte [] data = readInputStream (inStream); // obtain the binary data of the image
File imageFile = new File ("itcast.jpg"); // save it under the project
FileOutputStream outStream = new FileOutputStream (imageFile );
OutStream. write (data );
OutStream. close ();
}

Public static byte [] readInputStream (InputStream inStream) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream ();
Byte [] buffer = new byte [1024]; // defines a 1 K buffer.
Int len = 0;
While (len = inStream. read (buffer ))! =-1) {// the actual number of bytes returned
OutStream. write (buffer, 0, len); // write the data in the buffer to the memory.
}
InStream. close ();
Return outStream. toByteArray ();
}
}

On mobile phone
Button. setOnClickListener (new View. OnClickListener (){
@ Override
Public void onClick (View v ){
String path = pathText. getText (). toString ();
Try {
Byte [] data = ImageService. getImage (path );
Bitmap bitmap = BitmapFactory. decodeByteArray (data, 0, data. length); // generate a Bitmap
ImageView. setImageBitmap (bitmap); // display the image
} Catch (Exception e ){
Toast. makeText (ImageShowActivity. this, R. string. error, 1). show ();
Log. e (TAG, e. toString ());
}
}});
<! -- Access Network permissions -->
<Uses-permission android: name = "android. permission. INTERNET"/>


Public class StreamTool {

/**
* Retrieving data from the input stream
* @ Param inStream input stream
* @ Return
* @ Throws Exception
*/
Public static byte [] readInputStream (InputStream inStream) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream ();
Byte [] buffer = new byte [1024];
Int len = 0;
While (len = inStream. read (buffer ))! =-1 ){
OutStream. write (buffer, 0, len );
}
InStream. close ();
Return outStream. toByteArray ();
}
}
Bytes -----------------------------------------------------------------------------------------------------
Public class ImageService {
 
Public static byte [] getImage (String path) throws Exception {
URL url = new URL ("http://www.bkjia.com/uploadfile/2012/0419/20120419023209724.jpg ");
HttpURLConnection conn = (HttpURLConnection) url. openConnection ();
Conn. setRequestMethod ("GET ");
Conn. setConnectTimeout (5*1000 );
InputStream inStream = conn. getInputStream (); // obtain image data through the input stream
Return StreamTool. readInputStream (inStream); // obtain the binary data of the image.
}

}
B. Obtain webpages from the Internet (rarely used)
Byte [] data = readInputStream (inStream); // obtain the binary data of the webpage
String html = new String (data, "gb2312 ");


C. Obtain xml data from the network and display it on the mobile phone.
The android mobile phone simulator is bound to the simulator, so the local host cannot be used to access the web service.
Or 127.0.0.1. Instead, use the IP address on the LAN.
Public class VideoService {
/**
* Get the latest video information
* @ Return
* @ Throws Exception
*/
Public static List <Video> getLastVideos () throws Exception {
String path = "http: // 192.168.1.100: 8080/videoweb/video/list. do ";
URL url = new URL (path );
HttpURLConnection conn = (HttpURLConnection) url. openConnection ();
Conn. setReadTimeout (5*1000 );
Conn. setRequestMethod ("GET ");
InputStream inStream = conn. getInputStream ();
Return parseXML (inStream );
}
/**
* Parse the Protocol returned by the server to obtain video information.
* @ Param inStream
* @ Return
* @ Throws Exception
*/
Private static List <Video> parseXML (InputStream inStream) throws Exception {
List <Video> videos = null;
Video video = null;
XmlPullParser parser = Xml. newPullParser ();
Parser. setInput (inStream, "UTF-8 ");
Int eventType = parser. getEventType (); // generates the first event
While (eventType! = XmlPullParser. END_DOCUMENT) {// as long as it is not a document end event
Switch (eventType ){
Case XmlPullParser. START_DOCUMENT:
Videos = new ArrayList <Video> ();
Break;
 
Case XmlPullParser. START_TAG:
String name = parser. getName (); // gets the name of the element currently pointed to by the parser.
If ("video". equals (name )){
Video = new Video ();
Video. setId (new Integer (parser. getAttributeValue (0 )));
}
If (video! = Null ){
If ("title". equals (name )){
Video. setTitle (parser. nextText (); // gets the value of the next text node that the parser currently points.
}
If ("timelength". equals (name )){
Video. setTime (new Integer (parser. nextText ()));
}
}
Break;

Case XmlPullParser. END_TAG:
If ("video". equals (parser. getName ())){
Videos. add (video );
Video = null;
}
Break;
}
EventType = parser. next ();
}
Return videos;
}
}

D. Obtain json data from the network and display it on the mobile phone.

Public class VideoService {
/**
* Get the latest video information
* @ Return
* @ Throws Exception
*/
 
Public static List <Video> getJSONLastVideos () throws Exception {
List <Video> videos = new ArrayList <Video> ();
String path = "http: // 192.168.1.100: 8080/videoweb/video/list. do? Format = json ";
URL url = new URL (path );
HttpURLConnection conn = (HttpURLConnection) url. openConnection ();
Conn. setReadTimeout (5*1000 );
Conn. setRequestMethod ("GET ");
InputStream inStream = conn. getInputStream ();
Byte [] data = StreamTool. readInputStream (inStream );
String json = new String (data );
JSONArray array = new JSONArray (json );
For (int I = 0; I <array. length (); I ++ ){
JSONObject item = array. getJSONObject (I );
Int id = item. getInt ("id ");
String title = item. getString ("title ");
Int timelength = item. getInt ("timelength ");
Videos. add (new Video (id, title, timelength ));
}
Return videos;
}
 
}

 
From the treasure Valley

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.