Android Network Programming (2) HttpClient and HttpURLConnection

Source: Internet
Author: User

Android Network Programming (2) HttpClient and HttpURLConnection
Preface

In the previous article, we learned about the principles of the HTTP protocol. In this article, we will talk about HttpClient of Apache and HttpURLConnection of Java. These two types are commonly used in the request network. Both our encapsulated network request classes and third-party network request frameworks cannot be separated from these two class libraries.

1. HttpClient

The Android SDK contains HttpClient. The HttpClient class library is directly deleted in Android6.0. If you still want to use it, the solution is as follows:

If eclipse is used, add org. apache. http. legacy. jar to libs.
This jar package is in the ** sdk \ platforms \ android-23 \ optional Directory (you need to download android
6.0 SDK) If android studio is used, add:
   android {       useLibrary 'org.apache.http.legacy'        } 
HttpClient GET request

First, we will use the DefaultHttpClient class to instantiate an HttpClient and configure the default request parameters:

// Create HttpClient private HttpClient createHttpClient () {HttpParams mDefaultHttpParams = new BasicHttpParams (); // set connection timeout HttpConnectionParams. setConnectionTimeout (mDefaultHttpParams, 15000); // set the request timeout value to HttpConnectionParams. setSoTimeout (mDefaultHttpParams, 15000); HttpConnectionParams. setTcpNoDelay (mDefaultHttpParams, true); HttpProtocolParams. setVersion (mDefaultHttpParams, HttpVersion. HTTP_1_1); HttpProtocolParams. setContentCharset (mDefaultHttpParams, HTTP. UTF_8); // continuous handshake HttpProtocolParams. setUseExpectContinue (mDefaultHttpParams, true); HttpClient mHttpClient = new DefaultHttpClient (mDefaultHttpParams); return mHttpClient ;}

Next, create HttpGet and HttpClient, request the network, obtain HttpResponse, and process HttpResponse:

Private void useHttpClientGet (String url) {HttpGet mHttpGet = new HttpGet (url); mHttpGet. addHeader ("Connection", "Keep-Alive"); try {HttpClient mHttpClient = createHttpClient (); HttpResponse mHttpResponse = route cute (mHttpGet); HttpEntity response = mHttpResponse. getEntity (); int code = mHttpResponse. getStatusLine (). getStatusCode (); if (null! = MHttpEntity) {InputStream mInputStream = mHttpEntity. getContent (); String respose = converStreamToString (mInputStream); Log. I ("wangshu", "Request status code:" + code + "\ n request result: \ n" + respose); mInputStream. close () ;}} catch (IOException e) {e. printStackTrace ();}}

The converStreamToString method converts the request result to the String type:

private String converStreamToString(InputStream is) throws IOException {        BufferedReader reader = new BufferedReader(new InputStreamReader(is));        StringBuffer sb = new StringBuffer();        String line = null;        while ((line = reader.readLine()) != null) {            sb.append(line + "\n");        }        String respose = sb.toString();        return respose;    }

Finally, we enable thread access to Baidu:

  new Thread(new Runnable() {            @Override            public void run() {                useHttpClientGet("http://www.baidu.com");            }        }).start();

The returned result of the request. The Request status code is 200, and the result is an html page. Here, only part of the html code is intercepted:

The GET request parameters are exposed in the URL, which is not appropriate, and the URL length is limited: the length is within 2048 characters, and there is no limit on the URL length after HTTP 1.1. Generally, POST can replace GET. Next let's look at the POST request of HttpClient.

HttpClient POST request

THE post request AND get request are similar to the parameters to be passed:

Private void useHttpClientPost (String url) {HttpPost mHttpPost = new HttpPost (url); mHttpPost. addHeader ("Connection", "Keep-Alive"); try {HttpClient mHttpClient = createHttpClient (); List
  
   
PostParams = new ArrayList <> (); // The parameter postParams to be passed. add (new BasicNameValuePair ("username", "moon"); postParams. add (new BasicNameValuePair ("password", "123"); mHttpPost. setEntity (new UrlEncodedFormEntity (postParams); HttpResponse mHttpResponse = mHttpClient.exe cute (mHttpPost); HttpEntity mHttpEntity = mHttpResponse. getEntity (); int code = mHttpResponse. getStatusLine (). getStatusCode (); if (null! = MHttpEntity) {InputStream mInputStream = mHttpEntity. getContent (); String respose = converStreamToString (mInputStream); Log. I ("wangshu", "Request status code:" + code + "\ n request result: \ n" + respose); mInputStream. close () ;}} catch (IOException e) {e. printStackTrace ();}}
  
2. HttpURLConnection

Before Android 2.2, HttpURLConnection had some annoying bugs. For example, when you call the close () method for a readable InputStream, the connection pool may become invalid. The common solution is to disable the connection pool function directly:

Private void disableConnectionReuseIfNecessary () {// This is a bug before version 2.2 if (Integer. parseInt (Build. VERSION. SDK) <Build. VERSION_CODES.FROYO) {System. setProperty ("http. keepAlive "," false ");}}

Therefore, using HttpClient in Android 2.2 and earlier versions is a good choice. In Android 2.3 and later versions, HttpURLConnection is the best choice. Its API is simple and small, therefore, it is very suitable for Android projects. The compression and cache mechanisms can effectively reduce network access traffic and play a major role in improving speed and saving power. In Android 6.0, the HttpClient library is removed, and HttpURLConnection is our only choice in the future.

HttpURLConnection POST request

Because the HttpURLConnection POST request is sent, the GET request will be sent. So I will only give the POST example here.
First, create a UrlConnManager class, and then provide the getHttpURLConnection () method to configure the default parameters and return HttpURLConnection:

Public static HttpURLConnection getHttpURLConnection (String url) {HttpURLConnection mHttpURLConnection = null; try {URL mUrl = new URL (url); mHttpURLConnection = (HttpURLConnection) mUrl. openConnection (); // set the connection timeout value. setConnectTimeout (15000); // sets the read timeout value for mHttpURLConnection. setReadTimeout (15000); // set the request parameter mHttpURLConnection. setRequestMethod ("POST"); // Add the Header mHttpURLConnection. setRequestProperty ("Connection", "Keep-Alive"); // receives the input stream mHttpURLConnection. setDoInput (true); // enable mHttpURLConnection when passing parameters. setDoOutput (true);} catch (IOException e) {e. printStackTrace ();} return mHttpURLConnection ;}

Because we want to send a POST request, we need to write a postParams () method in the UrlConnManager class to organize the Request Parameters and write the request parameters to the output stream:

 public static void postParams(OutputStream output,List
  
   paramsList) throws IOException{       StringBuilder mStringBuilder=new StringBuilder();       for (NameValuePair pair:paramsList){           if(!TextUtils.isEmpty(mStringBuilder)){               mStringBuilder.append("&");           }           mStringBuilder.append(URLEncoder.encode(pair.getName(),"UTF-8"));           mStringBuilder.append("=");           mStringBuilder.append(URLEncoder.encode(pair.getValue(),"UTF-8"));       }       BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(output,"UTF-8"));       writer.write(mStringBuilder.toString());       writer.flush();       writer.close();   }
  

Next we will add the request parameters, call the postParams () method to organize the Request Parameters and send them to the output stream of HttpURLConnection, request the connection, and process the returned results:

Private void useHttpUrlConnectionPost (String url) {InputStream mInputStream = null; HttpURLConnection mHttpURLConnection = UrlConnManager. getHttpURLConnection (url); try {List
  
   
PostParams = new ArrayList <> (); // The parameter postParams to be passed. add (new BasicNameValuePair ("username", "moon"); postParams. add (new BasicNameValuePair ("password", "123"); UrlConnManager. postParams (mHttpURLConnection. getOutputStream (), postParams); mHttpURLConnection. connect (); mInputStream = mHttpURLConnection. getInputStream (); int code = mHttpURLConnection. getResponseCode (); String respose = converStreamToString (mInputStream); Log. I ("wangshu", "Request status code:" + code + "\ n request result: \ n" + respose); mInputStream. close ();} catch (IOException e) {e. printStackTrace ();}}
  

Finally, enable the thread request network:

 private void useHttpUrlConnectionGetThread() {        new Thread(new Runnable() {            @Override            public void run() {                useHttpUrlConnectionPost("http://www.baidu.com");            }        }).start();    }

Here we still request Baidu to see what will happen?

The Code mInputStream = mHttpURLConnection. getInputStream () reports an error and the file cannot be found. Open Fiddler for analysis. If you do not understand the principles of Fiddler and HTTP, please refer to Android Network Programming (I) HTTP protocol principles.

Our request message:

It seems that the request message is correct. Let's take a look at the Response Message:

Error 504 is reported. An error is returned when the data in the response is read. For this request, the server cannot return the complete response, and the returned data is 0 bytes. Therefore, mHttpURLConnection. getInputStream () cannot read the input stream of the server response. Of course this error is normal, and Baidu has no reason to process our POST request.

Download github source code

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.