The use and encapsulation of httpurlconnection and httpclient in Android _android

Source: Internet
Author: User
Tags readline

1. Written in front

Most andriod applications require data interaction with the server, HTTP, FTP, SMTP or directly based on socket programming can be data interaction, but HTTP is necessarily the most widely used protocol.
This article does not focus on the content of HTTP protocol, only discusses two ways of using HTTP protocol to access network in Android development--httpurlconnection and HttpClient
Because you need to access the network, add the following permissions in the Androidmanifest.xml

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


2.1 Get Way

Import; The following code implements a get way to initiate an HTTP request//connection network that is time-consuming and generally creates a new thread for private void Connectwithhttpurlconnection () {New Thread (
      {@Override public void run () {httpurlconnection connection = null;
        The OpenConnection method of try {//Call URL object gets httpurlconnection instance url url = new URL ("Http://");
        Connection = (httpurlconnection) url.openconnection ();
        Sets the request mode, GET or post Connection.setrequestmethod ("get");
        Sets the time of the connection timeout, read timeout, in milliseconds (ms) connection.setconnecttimeout (8000);
        Connection.setreadtimeout (8000);
        The getInputStream method gets the input stream returned by the server InputStream in = Connection.getinputstream (); Read the returned data stream by using the BufferedReader object read by row, stored in Stringbuider object response BufferedReader reader = new Bufferedreade
        R (New InputStreamReader (in)); StrinGbuilder response = new StringBuilder ();
        String Line;
        while (line = Reader.readline ())!= null) {response.append (line);
        ////... omit the code to process the data//If you need to update the UI, pass the data back to the main thread, and search for Android multithreaded programming} catch (Exception e) {
      E.printstacktrace ();
        finally {if (connection!= null) {//end, close connection connection.disconnect ();
}}}). Start ();

2.2 Post Method

Change the corresponding part to
Connection.setrequestmethod ("POST");
DataOutputStream data = new DataOutputStream (Connection.getoutputstream ());
Data.writebytes ("Stu_no=12345&stu_name=tom");

Pass in & separate multiple parameters
If you need to pass in complex parameters, you can use JSON, a description of the use of JSON, and refer to one of my other essays JSON parsing two methods.

3.1 Get Way

Import org.apache.http.client.HttpClient;
Import Org.apache.http.client.methods.HttpGet;
Import org.apache.http.impl.client.DefaultHttpClient;
Import Org.apache.http.HttpResponse;
Import org.apache.http.HttpEntity;
Import Org.apache.http.HttpStatus;
Create Defaulthttpclient instance
httpclient httpclient = new Defaulthttpclient ();   
Incoming URLs, and then execute
httpget httpget = new HttpGet ("Http://");
HttpResponse HttpResponse = Httpclient.execute (httpget); 
The request result is judged by the status code,
//Common status Code 200 request succeeded, 404 Page Not Found
//More status code on HTTP direct Google
if (Httpresponse.getstatusline (). Getstatuscode () = = HTTPSTATUS.SC_OK) {    
  //request succeeded, use Httpentity to get Return data
  //Use Entityutils to convert return data to string
  httpentity entity = httpresponse.getentity (); 
  String response = entityutils.tostring (entity);
  If it is Chinese, specify the encoding 
  //==>string response = entityutils.tostring (entity, "Utf-8"); 

3.2 Post Method

Import org.apache.http.client.HttpClient;
Import Org.apache.http.client.methods.HttpPost;
Import Org.apache.http.HttpResponse;
Import Org.apache.http.NameValuePair;
Import org.apache.http.client.entity.UrlEncodedFormEntity;
Import Org.apache.http.message.BasicNameValuePair;
HttpClient httpclient = new Defaulthttpclient ();
HttpPost HttpPost (""); 
Use Namevaluepair (key pair) to store parameters
list<namevaluepair> data = new arraylist<namevaluepair> ();
Add key values to
Data.add (new Basicnamevaluepair ("Stu_no", 12345));
Data.add (New Basicnamevaluepair ("Stu_name", "Tom"));
Use the Setentity method to pass the encoded parameter
httppost.setentity (new urlencodedformentity (data, "Utf-8"); 
Executes the POST request
HttpResponse HttpResponse = Httpclient.execute (httppost);
// ..... Omit the code that handles HttpResponse, consistent with Get mode

3.3 Android 6.0 Removal httpclient

The Android 6.0 (API 23) version of the SDK has removed the Apache HttpClient-related classes, and the solution is Google and recommends the use of httpurlconnection.
If you need to use this class, click to see the solution.
4.HttpURLConnection Combat
If you've ever used jquery (a javasript library), you must be impressed with jquery's web programming, like an HTTP request with just the following lines of code.

jquery's Post method
$.post ("Http://", {
    "stu_no": 12345,
    "Stu_name": "Tom",
  }). Done ( function () {
    //... Request successful Code
  }). Fail (function () {
    //... Request failed Code
  }). Always (function () {
    //... Code that always executes

Of course we don't want to write down 2.1 of those cumbersome code every time a Web request is written, can Android's HTTP requests be as simple as jquery? Of course! The following code implements the HttpURLConnection HTTP request method Encapsulation:

4.1 Defines the interface Httpcallbacklistener, in order to implement the callback

Defines the Httpcallbacklistener interface
//contains two methods, and the successful and failed callback functions define public
interface Httpcallbacklistener {
  void OnFinish (String response);
  void OnError (Exception e);

4.2 Create Httptool class, abstract request method (get)

Import; /* Create a new class Httptool to abstract common operations * to avoid the need to instantiate when calling the SendRequest method, set to static method * Incoming Httpcallbacklistener object for method callback * Because network requests are more time-consuming, generally in child threads 
      * To get the data returned by the server, you need to use the Java callback mechanism */public class Httptool {public static void SendRequest (final String address,
        Final Httpcallbacklistener Listener {new Thread (new Runnable () {@Override public void run () {
        HttpURLConnection connection = null;
          try {URL url = new URL (address);
          Connection = (httpurlconnection) url.openconnection ();
          Connection.setrequestmethod ("get");
          Connection.setconnecttimeout (8000);
          Connection.setreadtimeout (8000);
          InputStream in = Connection.getinputstream ();
          BufferedReader reader = new BufferedReader (new InputStreamReader (in)); StringBuilder response = new StringBuilder();
          String Line;
          while (line = Reader.readline ())!= null) {response.append (line);
          } if (listener!= null) {//callback method OnFinish () Listener.onfinish (response.tostring ()); } catch (Exception e) {if (listener!= null) {//callback method OnError () List
          Ener.onerror (e);
          finally {if (connection!= null) {connection.disconnect ());
  }}}). Start ();

4.3 Invocation Example

Use this httptool to initiate a GET request
String url = "Http://";
Httptool.sendrequest (url,new Httpcallbacklistener () {
  @Override public 
  void OnFinish (String response) {
    // ... The processing code for the returned result is omitted 
  @Override public 
  void OnError (Exception e) {  
    //... Omit processing code for request failure

4.4 Abstract Request Method (POST)

/* Add a parameter params on the basis of the Get method implementation,
 * You can also pass the parameter to a string and pass in the
 key-value pair collection, then deal with
/public static void SendRequest (final String address,
  final string params, final Httpcallbacklistener listener) {

The above is the entire content of this article, I hope to help you learn.

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: 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.