Access Network Resources through HTTP in Android Development

Source: Internet
Author: User

Access Network Resources through HTTP in Android Development

Use HTTP to access network resources

Previously, we introduced that URLConnection can easily exchange information with specified sites. URLConnection also has a subclass: HttpURLConnection and HttpURLConnection are further improved based on LIRLConnection, added some convenient methods for operating http resources.

1. Use HttpURLConnection

HttpURLConnection inherits URLConnection and can be used to send a GET request POST request to a specified website. It provides the following convenient methods based on URLConnection.

1) Int getResponseCode (): Get the response code of the server.

2) String getResponseMessage (): gets the Server Response Message.

3) String getRequestMethod (): gets the method for sending a request.

4) void setRequestMethod (String method): sets the method for sending requests.

The following is a practical example to demonstrate how to use HttpURLConnection to implement multi-threaded download.

1.1 instance: multi-thread download

Multi-threaded download can be used to download files more quickly. Because the client starts multiple threads for freezing, the server also needs to provide services for the client. Assume that the server can serve a maximum of 100 users at the same time. One thread on the server corresponds to one user, and the other 100 threads are concurrently executed in the computer, that is, the history of CPU division is executed in turn, if app A uses 99 threads to download files, the download speed would naturally be faster if app A occupies 99 user resources.

Tip: in fact, the more concurrent download threads the client receives, the faster the program downloads, because after too many concurrent threads are enabled on the client, the application needs to maintain the overhead of each thread and the overhead of thread synchronization, which will lead to lower download speed.

1.2 to implement multi-threaded download, the program can be performed as follows:

? Create a URL object.

? Obtains the size of the resource pointed to by the specified URL object (implemented by the getContentLength () method). The HttpURLConnection class is used here.

? Create an empty file of the same size as the network resource on the local disk.

? Calculate the part of the network resource that each thread should download (starting from which byte and ending with which byte), create and start multiple threads in sequence to download the specified part of the network resource.

1.2 The download tool Code provided by this program is as follows.
Package com.jph.net; import java. io. inputStream; import java. io. randomAccessFile; import java.net. httpURLConnection; import java.net. URL;/*** Description: * Create the main class of the ServerSocket listener * @ author jph * Date: 2014.08.27 */public class DownUtil {/** download resource path **/private String path;/** save location of the downloaded file **/private String targetFile; /** how many threads need to be used to download resources **/private int threadNum;/** download thread object **/private DownThread [] threads;/** total number of downloaded files Size **/private int fileSize; public DownUtil (String path, String targetFile, int threadNum) {this. path = path; this. threadNum = threadNum; // initialize the threads array threads = new downthread1_threadnum1_1_this.tar getFile = targetFile;} public void download () throws Exception {URL url = new URL (path ); httpURLConnection conn = (HttpURLConnection) url. openConnection (); conn. setConnectTimeout (5*1000); conn. setRequestMethod ("GET"); conn. setRequestProperty ("Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg," + "application/x-shockwave-flash, application/xaml + xml, "+" application/vnd. ms-xpsdocument, application/x-ms-xbap, "+" application/x-ms-application, application/vnd. ms-excel, "+" application/vnd. ms-powerpoint, application/msword, */* "); conn. setRequestProperty ("Accept-Language", "zh-CN"); conn. setRequestProper Ty ("Charset", "UTF-8"); conn. setRequestProperty ("Connection", "Keep-Alive"); // obtain the file size fileSize = conn. getContentLength (); conn. disconnect (); int currentPartSize = fileSize/threadNum + 1; RandomAccessFile file = new RandomAccessFile (targetFile, "rw"); // set the local file size file. setLength (fileSize); file. close (); for (int I = 0; I <threadNum; I ++) {// calculate the start position of download for each thread, int startPos = I * currentPartSize; // each thread uses a Rand OmAccessFile: Download RandomAccessFile currentPart = new RandomAccessFile (targetFile, "rw"); // locate the download location of the thread currentPart. seek (startPos); // create the download thread threads [I] = new DownThread (startPos, currentPartSize, currentPart); // start the download thread threads [I]. start () ;}/// get the download completion percentage public double getCompleteRate () {// count the total size of multiple threads that have been downloaded int sumSize = 0; for (int I = 0; I <threadNum; I ++) {sumSize + = threads [I]. length;} // return the percentage of completed return sumSi Ze * 1.0/fileSize;} private class DownThread extends Thread {/** download location of the current Thread **/private int startPos; /** defines the file size that the current thread is responsible for downloading **/private int currentPartSize;/** the file block to be downloaded by the current thread **/private RandomAccessFile currentPart; /** define the number of bytes downloaded by this thread **/public int length; public DownThread (int startPos, int currentPartSize, RandomAccessFile currentPart) {this. startPos = startPos; this. currentPartSize = currentPartSize; this. currentP Art = currentPart;} @ Overridepublic void run () {try {URL url = new URL (path); HttpURLConnection conn = (HttpURLConnection) url. openConnection (); conn. setConnectTimeout (5*1000); conn. setRequestMethod ("GET"); conn. setRequestProperty ("Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg," + "application/x-shockwave-flash, application/xaml + xml, "+" application/vnd. ms-xpsdocument, application/x-ms-xbap, "+" Application/x-ms-application, application/vnd. ms-excel, "+" application/vnd. ms-powerpoint, application/msword, */* "); conn. setRequestProperty ("Accept-Language", "zh-CN"); conn. setRequestProperty ("Charset", "UTF-8"); InputStream inStream = conn. getInputStream (); // skip the startPos byte, indicating that the thread only downloads the part of the file that it is responsible. InStream. skip (this. startPos); byte [] buffer = new byte [1024]; int hasRead = 0; // reads network data, and write the while (length <currentPartSize & (hasRead = inStream. read (buffer)> 0) {currentPart. write (buffer, 0, hasRead); // The total download size of this thread. length + = hasRead;} currentPart. close (); inStream. close ();} catch (Exception e) {e. printStackTrace ();}}}}

The DownUtil tool class contains a DownloadThread internal class, which is responsible for opening the input stream of remote resources in the run () method of the internal class, and calling the inputStream skip (int) the method skips the specified number of bytes so that the thread can read the part downloaded by itself.

After providing the DownUtil tool class, you can call the DownUtil class in the Activity to execute the download task. The Program Interface contains two text boxes and one is used to enter the Source Path of the network file, another file name is used to specify the file to be downloaded to the local device. The interface of the program is relatively simple, so the interface layout code is no longer provided. The Activity code of this program is as follows.

Package com.jph.net; import java. util. timer; import java. util. timerTask; import android. app. activity; import android. content. context; import android. OS. bundle; import android. OS. handler; import android. OS. logoff; import android. OS. message; import android. view. view; import android. view. view. onClickListener; import android. widget. button; import android. widget. editText; import android. widget. progressBar; import android. widget. toast;/*** Description: * multi-threaded download * @ author jph * Date: 2014.08.27 */public class MultiThreadDown extends Activity {EditText url; EditText target; Button downBn; ProgressBar; downUtil downUtil; private int mDownStatus; @ Overridepublic void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); // obtain the url = (EditText) findViewById (R. id. url); target = (EditText) findViewById(R.id.tar get); downBn = (Button) findViewById (R. id. down); bar = (ProgressBar) findViewById (R. id. bar); // create a Handler object final Handler handler = new Handler () {@ Overridepublic void handleMessage (Message msg) {if (msg. what = 0x123) {bar. setProgress (mDownStatus) ;}}; downBn. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {// initialize the DownUtil object (the last parameter specifies the number of threads) downUtil = new DownUtil (url. getText (). toString (), target. getText (). toString (), 6); new Thread () {@ Overridepublic void run () {try {// start downloading downUtil. download ();} catch (Exception e) {e. printStackTrace ();} // defines the progress of system completion obtained by scheduling every second. final Timer timer = new Timer (); timer. schedule (new TimerTask () {@ Overridepublic void run () {// obtain the download task completion rate double completeRate = downUtil. getCompleteRate (); mDownStatus = (int) (completeRate * 100); // update the progress bar handler on the Send Message notification page. sendEmptyMessage (0x123); // After the download is complete, cancel the task scheduling if (mDownStatus> = 100) {showToastByRunnable (MultiThreadDown. this, "download completed", 2000); timer. cancel () ;}}, 0,100 );}}. start ();}});} /*** use Toast * @ param context * @ param text in a non-UI thread to display the message content * @ param duration the message display time **/private void showToastByRunnable (final Context context, final CharSequence text, final int duration) {Handler handler = new Handler (logoff. getMainLooper (); handler. post (new Runnable () {@ Override public void run () {Toast. makeText (context, text, duration ). show ();}});}}

The above Activity not only uses DownUtil to control program download, but also starts a timer, which controls the download progress every 0.1 seconds, the progress bar in the program is used to display the download progress of the task.

The program not only needs to access the network, but also needs to access the system SD card and create files in the SD card. Therefore, the program must be granted the permissions to access the network and access the SD card files:

 
 
 
 
 
 

Program running:


Tip: The above program has implemented the core code for multi-threaded download. If you want to implement breakpoint download, you also need to add a configuration file (you can find that all the breakpoint download tools will generate two files starting from the download: one is an empty file of the same size as the network resources, configuration file), which records the bytes that each thread has downloaded. When the network is disconnected and the download starts again, each thread can be downloaded backward Based on the recorded position in the configuration file.

2. Use ApacheHttpClient

In general, if you only need to submit a request to a simple page of the Web site and obtain the server response, you can use the HttpURLConnection described earlier. However, in most cases, Web pages on the Web site may not be as simple as they are accessible through a simple URL, you may need to log on and have the required permissions to access this page. In this case, Session and Cookie processing are required. If you plan to use HttpURLConnection to handle these details, it is also possible to implement it, but it is difficult to process it.

To better handle requests to Web sites, including Session, Cookie, and other details, the Apache open-source organization provides an HttpClient project. You can see the name of the project, it is a simple HTTP client (not a browser) that can be used to send HTTP requests and receive HTTP responses. However, the server's response will not be cached, the JavaScript code embedded in the HTML page cannot be executed, and the page content will not be parsed or processed.

Tip: in simple terms, HttpClient is an enhanced version of HttpURLConnection. HttpURLConnection can do all the things HttpClient can do. HttpURLConnection does not provide some functions, and HttpClient also provides, however, it only focuses on how to send requests, receive responses, and manage HTTP connections. |

Android integrates HttpClient. developers can directly use HttpCHent in Android applications to access and submit requests and receive responses.

2.1 it is easy to use HttpClient to send a clear request and receive a response. You only need to perform the following steps:

1) Create an HttpClient object.

2) to send a GET request, create an HttpGet object. To send a POST request, create an HttpPost object.

3) if you need to send request parameters, you can use the setParams (HttpParams params) method of HttpGet and HttpPost to add request parameters. For HttpPost objects, you can also call setEntity (HttpEntityentity) method To Set Request parameters.

4) Call the execute (HttpUriRequestrequest) of the HttpClient object to send a request and execute this method to return an HttpResponse.

5) Call the getAllHeaders () and getHeaders (String name) Methods of HttpResponse to obtain the response header of the server. Call the getEntity () method of HttpResponse to obtain the HttpEntity object, this object encapsulates the response content of the server. The program can get the server response content through this object.

2.2 instance: access protected resources

The following Android app needs to send a request to a specified page, but this page is not a simple page, only when the user has logged on, this page is accessible only when the username of the logged-on user is jph. If you use HttpUrlConnection to access this page, the details to be processed are too complicated. The following uses HttpClient to access protected pages.

Accessing Protected pages in Web applications is simple if you use a browser. When you log on to the system through the logon page provided by the system, the browser is responsible for maintaining the Session with the server, if the user name and password meet the requirements, you can access protected resources.

In order to access the protected page through HttpClient, the program also needs to use HttpClient to log on to the system. As long as the application uses the same HttpClient to send requests, HttpClient automatically maintains the Session status with the server, that is to say, after the program logs on to the system with HttpCHent for the first time, it can access the protected page with HttpCHent.

Tip: although the instance provided here only accesses the protected page, accessing other protected resources is similar. If the program logs on to the system through HttpClient for the first time, next, you can use the HttpClient to access protected resources.

2.3 program code:

Package com.jph.net; import java. io. bufferedReader; import java. io. inputStreamReader; import java. util. arrayList; import java. util. list; import org. apache. http. httpEntity; import org. apache. http. httpResponse; import org. apache. http. nameValuePair; import org. apache. http. client. httpClient; import org. apache. http. client. entity. urlEncodedFormEntity; import org. apache. http. client. methods. httpGet; import org. apache. Http. client. methods. httpPost; import org. apache. http. impl. client. defaultHttpClient; import org. apache. http. message. basicNameValuePair; import org. apache. http. protocol. HTTP; import org. apache. http. util. entityUtils; import android. app. activity; import android. app. alertDialog; import android. content. dialogInterface; import android. OS. bundle; import android. OS. handler; import android. OS. logoff; import android. o S. message; import android. text. html; import android. view. view; import android. widget. editText; import android. widget. textView; import android. widget. toast;/*** Description: * use HttpClient to access protected network resources * @ author jph * Date: 2014.08.28 */public class HttpClientDemo extends Activity {TextView response; HttpClient httpClient; handler handler = new Handler () {public void handleMessage (Message msg) {if (msg. what = 0 X123) {// use the response text box to display the server response. append (Html. fromHtml (msg. obj. toString () + "\ n") ;}};@ Overridepublic void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); // create the DefaultHttpClient object httpClient = new DefaultHttpClient (); response = (TextView) findViewById (R. id. response);}/*** this method is used to respond to the "access page" button **/public void accessSecret (View v) {response. setText (""); New Thread () {@ Overridepublic void run () {// create an HttpGet object HttpGet = new HttpGet ("http: // 10.201.1.32: 8080/HttpClientTest_Web/secret. jsp "); // ① try {// send the GET request HttpResponse httpResponse = httpClient.exe cute (get); // ② HttpEntity entity = httpResponse. getEntity (); if (entity! = Null) {// read Server Response BufferedReader br = new BufferedReader (new InputStreamReader (entity. getContent (); String line = null; while (line = br. readLine ())! = Null) {Message msg = new Message (); msg. what = 0x123; msg. obj = line; handler. sendMessage (msg) ;}} catch (Exception e) {e. printStackTrace ();}}}. start ();}/*** this method is used to respond to the "log on to system" button **/public void showLogin (View v) {// load the logon page final View loginDialog = getLayoutInflater (). inflate (R. layout. login, null); // use the dialog box to log on to the new AlertDialog system. builder (HttpClientDemo. this ). setTitle ("log on to the system "). setView (loginDialog ). setPositiveButton ("login", new DialogInterface. onClickListener () {@ Overridepublic void onClick (DialogInterface dialog, int which) {// obtain the user name and password final String name = (EditText) loginDialog. findViewById (R. id. name )). getText (). toString (); final String pass = (EditText) loginDialog. findViewById (R. id. pass )). getText (). toString (); new Thread () {@ Overridepublic void run () {try {HttpPost post = new HttpPost ("http: // 10.201.1.32: 8080/" + "HttpClientTest_Web/login. jsp "); // ③ // if the number of passed parameters is large, you can encapsulate the List of passed parameters.
 
  
Params = newArrayList
  
   
(); Params. add (new BasicNameValuePair ("name", name); params. add (new BasicNameValuePair ("pass", pass); // set the request parameter post. setEntity (new UrlEncodedFormEntity (params, HTTP. UTF_8); // send the POST request HttpResponse response = httpClient.exe cute (post); // ④ // if the server returns the response if (response. getStatusLine (). getStatusCode () == 200) {String msg = EntityUtils. toString (response. getEntity (); loiter. prepare (); // prompt that the logon is successful Toast. makeText (HttpClientDemo. this, msg, Toast. LENGTH_SHORT ). show (); logoff. loop () ;}} catch (Exception e) {e. printStackTrace ();}}}. start ();}}). setNegativeButton ("cancel", null ). show ();}}
  
 

In the above program, an HttpGet object is created in the bold characters ① and ②, and then the program calls the execute () method of HttpClient to send a GET request; in the program, a HttpPost object is created in bold characters ③ and ④, and then the program calls the execute () method of HttpClient to send the POST request. The above GET request is used to obtain the protected page on the server, and the POST request is used to log on to the system.

Run the program and click "access page" to view the page shown in.


As you can see, the program directly sends a request to the secret. jsp of the specified Web application, and the program will not be able to access the protected page, so the page shown is displayed. Click the "Log on" button on the page shown in. The logon dialog box shown in is displayed.

Enter "jph" and "123" in the two input boxes in the displayed dialog box, and then click "Log on. the jsp page sends a POST request and uses the user name and password entered by the user as the request parameter. If the user name and password are correct, you can see the logon success prompt.


After successful logon, HttpClient automatically maintains the connection with the server and maintains the Session status with the server. Then, click the "access page" button in the program again, the output shown in is displayed.


As you can see, at this time, you can use HttpClient to send a GET request to normally access protected resources. This is because HttpClient was used to log on to the system, and HttpClient can maintain Session connections with the server.

From the above programming process, it is not difficult to see that using HttpClient of Apache is simpler, and it provides more functions than HttpURLConnection.

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.