Android use HttpURLConnection Class View network pictures and network source code

Source: Internet
Author: User

1. First, to introduce the HttpURLConnection class, the HttpURLConnection class is located in the java.net package for sending HTTP requests and getting HTTP responses. Because this class is an abstract class, you cannot instantiate an object directly, so you need to use the OpenConnection () method of the URL to get it.

For example, to create a HttpURLConnection object that corresponds to a http://www.baidu.com Web site, you can use the following code:

URL url=new url ("http://www.baidu.com"); HttpURLConnection urlconnection= (httpurlconnection) url.openconnection ();
Note: The above code is created by the OpenConnection () method of the HttpURLConnection object, and does not actually perform the connection operation, just create a new instance, before the connection, you can also set some properties.

For example, when the connection timed out and how the request was requested, the code is as follows:

Urlconnection.setconnecttimeout (5000);//Set the connection time-out to 5 seconds Urlconnection.setrequestmethod ("get");//The way to set the connection is GET mode

Once you have created the HttpURLConnection object, you can use that object to send an HTTP request.



2. Before you write our Android project, do the following steps:

(1). Turn on the Tomcat server as shown in:

(2). Deploy the Web project we need to the Tomcat server, or copy our Web project to the WebApps directory under the installation directory of the Tomcat server, as shown in:

(3). This Android project to access for the music project, open this project as shown in:

One of the images that we want to access in Android is the image folder, and the index.jsp file under the music project, which is to view this network image and network source code.

(4). Finally, we have to know the IP address of the current network because we access the Web project for the Tomcat server under the Windows system, and the Android kernel is Linux, the system is not the same, so we access the Web ' project under Windows System, You can enter http://localhost:8083/music/index.jsp or http://127.0.0.1:8083/music/index.jsp and http://192.168.91.1:8083/directly Music/index.jsp, while the Android Access Web project can only be accessed via http://192.168.91.1:8083/music/index.jsp so, first view our IP address, open the Command Line window, enter the ipconfig command , you can view it as shown in the following:

The IPV4 address that you see is the IP address.



3. Next we can write our Android project, this Android project is used to view network pictures and Web source, new Android project, project named Android_net, the main project structure is as follows:

(1). First, open our Activity_main.xml layout file, this layout file only placed two buttons, click the different buttons to jump to different activity, the code is as follows:

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    android:layout_width=" match_parent "    android:layout_height=" Match_parent "    android:orientation= "vertical" >    <button        android:id= "@+id/net_image"        android:layout_ Width= "Match_parent"        android:layout_height= "wrap_content"        android:text= "view network pictures"/>    <button        android:id= "@+id/net_code"        android:layout_width= "match_parent"        android:layout_height= "Wrap_ Content "        android:text=" View Network source code "/></linearlayout>


(2). Open the Mainactivity.java file, this class is used to click the button to jump different activity, the code is as follows:

Package Com.android.android_net;import Android.app.activity;import Android.content.intent;import android.os.Bundle ; Import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;public class Mainactivity extends Activity {private button net_image,net_code;//declares a Button object @overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main);/* Gets the two button control */net_image= (button) Findviewbyid (r.id.net_image) in the layout manager, net_code= (Button) Findviewbyid (r.id.net_ code);/* Add button click to listen Event */net_image.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View v) { Intent intent=new Intent (mainactivity.this,shownetimageactivity.class);//Instantiate Intent object StartActivity (Intent);// Open this activity, jump to Shownetimageactivity}); Net_code.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View v) {Intent intent=new Intent (mainactivity.this,shownetcodeactivity.class);//Instantiate Intent object StartActivity ( Intent);//start this activity, jump to the Shownetcodeactivity class}});}} 


(3). Next, in the layout directory, create a new Activity_image.xml file to display the image of the network, the main code is as follows:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "/http Schemas.android.com/apk/res/android "android:layout_width=" match_parent "android:layout_height=" Match_parent "and roid:orientation= "vertical" > <textview android:layout_width= "match_parent" android:layout_height= "Wrap_co Ntent "android:text=" Network picture path "android:padding=" 5DP "/><edittext android:id=" @+id/imagepath_et "Android:la Yout_width= "Match_parent" android:layout_height= "wrap_content" android:text= "http://192.168.91.1:8083/music/ Image/mm4.jpg "/><button android:id=" @+id/show_netimage "android:layout_width=" Match_parent "android:layout _height= "Wrap_content" android:text= "View network Pictures"/><imageview android:id= "@+id/imageview" android:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:src= "@drawable/ic_launcher"/></linearlayout 


(4). Next, create a new Shownetimageactivity class under the Com.android.android_net package, which opens a thread that calls ImageService's GetImage () method, In order to avoid the network main thread exception, the code is as follows:

Package Com.android.android_net;import Com.android.service.imageservice;import Android.app.activity;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import Android.os.bundle;import Android.view.View; Import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.edittext;import Android.widget.imageview;public class Shownetimageactivity extends Activity {private EditText imagepath_et;// Declares the EditText object, which is the picture path input box, private button show_netimage;//declares the button object private ImageView imageview;// Declare ImageView object @overrideprotected void OnCreate (Bundle savedinstancestate) {//TODO auto-generated method Stubsuper.oncreate (savedinstancestate); Setcontentview (r.layout.activity_image);/* Gets the various controls for the layout manager */imagepath_et= ( EditText) Findviewbyid (R.id.imagepath_et), show_netimage= (Button) Findviewbyid (r.id.show_netimage); imageview= ( ImageView) Findviewbyid (R.id.imageview);//Add Event Listener Show_netimage.setonclicklistener for button click (New Onclicklistener () {@ overridepublic void OnClick (View v) {//TODO auto-generated Method stubfinal String imagepath=imagepath_et.gettext (). toString ()//Get Picture path//Create new Thread New Runnable () {@Overridepublic void Run () {//TODO auto-generated method stubtry {byte[] Data=imageservice.getimage ( ImagePath);//Call the GetImage () method of the ImageService class to return the byte array final Bitmap bitmap=bitmapfactory.decodebytearray (data, 0, DATA.LENGTH);//Create a Bitmap object Imageview.post (new Runnable () {@Overridepublic void Run () {//TODO auto-generated method Stubimageview.setimagebitmap (bitmap);//Set the displayed picture});} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}). Start ();//Open Thread}});}}


(5). Then, the main ImageService class, under the Com.android.service package, is used to return the data for the network picture, with the following code:

Package Com.android.service;import Java.io.bytearrayoutputstream;import Java.io.inputstream;import Java.net.httpurlconnection;import Java.net.url;public class ImageService {public static byte[] GetImage (String ImagePath) throws Exception {//TODO auto-generated method stuburl url=new url (imagePath);// Instantiate the URL object urlhttpurlconnection connection= (httpurlconnection) url.openconnection ();// Instantiate the HttpURLConnection object Connectionconnection.setconnecttimeout (5000);//Set the connection time-out to 5 seconds Connection.setrequestmethod (" Get ");//Set request method is get mode int code=connection.getresponsecode ();//Get Status code//If the status code request succeeds, code equals HTTPURLCONNECTION.HTTP_OK Can also be written as code==200if (CODE==HTTPURLCONNECTION.HTTP_OK) {InputStream inputstream=connection.getinputstream ();//Get input stream, Returns a InputStream object Bytearrayoutputstream outputstream=new bytearrayoutputstream ();//Instantiate a byte array output input stream object byte[] buffer= New byte[1024];//instantiates a byte array object int len=0;//defines a variable with an initial value of 0//when the input stream is fetched with data, the loop writes the data while ((Len=inputstream.read (buffer))!=- 1) {outputstream.write (buffer, 0, Len);//Write Data}inputstream.cloSE ();//Close input stream return Outputstream.tobytearray ();//Return Data byte array}return null;}} 


(6). Then create a new Activity_code.xml file in the layout directory to display the network source code as follows:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Match_parent "android:layout_height=" match_parent "android:orientation=" vertical " > <textview android:layout_width= "match_parent" android:layout_height= "Wrap_content" Android :p adding= "5DP" android:text= "Network picture path:"/> <edittext android:id= "@+id/codepath_et" Android:lay Out_width= "Match_parent" android:layout_height= "wrap_content" android:text= "http://192.168.91.1:8083/music/i ndex.jsp "/> <button android:id=" @+id/show_netcode "android:layout_width=" Match_parent "Android oid:layout_height= "Wrap_content" android:text= "View network source"/> <scrollview android:layout_width= "match_p            Arent "android:layout_height=" wrap_content "> <textview android:id=" @+id/textview " Android:layout_width= "Match_parenT "android:layout_height=" wrap_content "android:text=" haha ... "/> </scrollview></linear Layout>


(7). Create a new Shownetcodeactivity class under the Com.android.android_net package, which opens a thread that uses the handler message mechanism to display our network source code. In which the new thread calls the GetCode () method of the Codeservice class to obtain the network source code, the Shownetcodeactivity class is as follows:

Package Com.android.android_net;import Android.app.activity;import Android.os.bundle;import Android.os.Handler; Import Android.os.message;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.edittext;import Android.widget.textview;import Com.android.service.codeservice;public class Shownetcodeactivity extends Activity {private EditText codepath_et;// Declare EditText object Private button show_netcode;//Declare button object private TextView textview;//declare TextView object private String result= "" ;//Initialize an empty string type variable private Handler handler;//declares a Handler object @overrideprotected void OnCreate (Bundle Savedinstancestate) {//TODO auto-generated method Stubsuper.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_code);/* Gets the individual controls in the Layout manager */codepath_et= (EditText) Findviewbyid (R.id.codepath_et); Show_netcode= ( button) Findviewbyid (R.id.show_netcode), textview= (TextView) Findviewbyid (R.id.textview);//Add Listener Event for button click Show_ Netcode.setonclicklistener (New Onclicklistener () {@overridepublic void OnClick (View v) {final String codepath=codepath_et.gettext (). toString ();//Get the path to the network source//create a new thread Thread (New Runnable () {@Overridepublic void Run () {//TODO auto-generated method stubtry {Result=codeservice.getcode ( Codepath);//Call the GetCode method of the Codeservice class to return the string data message msg=handler.obtainmessage ();/ Get Message Messages Handler.sendmessage (msg) via handler object;//Send Message} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}). Start ();//Open a thread//instantiate a Handler object Handler=new Handler () {@Overridepublic void Handlemessage (Message msg) {//TODO Auto-generated method Stubif (result!=null) {textview.settext (result);//Set text view to display text}super.handlemessage (msg);}};});}}


(8). Next, under the Com.android.service package, create a new Codeservice class, used to obtain the network source code, as follows:

Package Com.android.service;import Java.io.bytearrayoutputstream;import Java.io.inputstream;import Java.net.httpurlconnection;import Java.net.url;public class Codeservice {public static string GetCode (String codepath) Throws Exception {//TODO auto-generated method stuburl url=new url (codepath);//Instantiate a URL object httpurlconnection connection= (httpurlconnection) url.openconnection ();//Instantiate a HttpURLConnection object Connection.setconnecttimeout (5000);// Set the connection timeout to 5 seconds Connection.setrequestmethod ("get");//Set the connection way for the get mode int code=connection.getresponsecode ();//Get the status code// If the request succeeds if (code==200) {InputStream inputstream=connection.getinputstream ();//Gets the input stream, Returns the InputStream object Bytearrayoutputstream outputstream=new bytearrayoutputstream ();//Instantiates a Bytearrayoutputstream object byte [] buffer=new byte[1024];//instantiates a byte array object int len=0;//defines a variable with an initial value of 0//when the input stream obtained has data, the loop writes the data while ((Len=inputstream.read ( Buffer)!=-1) {outputstream.write (buffer, 0, Len),//write Data}inputstream.close ();//Close input stream byte[] Data= Outputstream.tobytearray ();//Get byte array string result=neW String (Data, "UTF-8");//A String object is instantiated by the obtained byte array data, the encoded format is Utf-8return result;//returns the data written}return null;}} 

(9). Finally, be sure to add access to the network in the Androidmanifest.xml file, as well as the two activity, the code is as follows:

To add access to network permissions:

<uses-permission android:name= "Android.permission.INTERNET"/>

Declare two additional activity:

<activity android:name= "Com.android.android_net. Shownetimageactivity "/> <activity android:name=" com.android.android_net. Shownetcodeactivity "/>


4. Deploy our project to the Android emulator with the following effects:

(1). Click the View Network Picture button to jump to shownetimageactivity as shown in:

Click on the button, such as:

Gets the picture on the Tomcat server.

(2). If you click on the button that you just started to view the Web source, you will jump to shownetcodeactivity, as shown in:

Click the Network Source button, such as:

This will get to the source of the network.

Note: One of the points to note is that when we access the source of the network files, we should pay attention to the network JSP file and get the encoding problem of the string, or there will be garbled problems in Chinese.



5. The above content is only for your study reference, write not good, please forgive me, if there are errors, please point out, thank you!

Source: http://download.csdn.net/download/u012561176/9054209




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

Android use HttpURLConnection Class View network pictures and network source code

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.