Android Network programming (ii) HttpClient and HttpURLConnection
Source: Internet
Author: User
<span id="Label3"></p><p><p>Related articles<br>Android Network Programming (i) HTTP protocol principle</p></p><strong><strong>Preface</strong></strong><p><p>In the previous article we learned about the principle of HTTP protocol, This one we talk about Apache HttpClient and Java httpurlconnection, both of which we normally request the network will Use. Whether we are our own encapsulated network request class or a Third-party network request framework, These two class libraries are inseparable.</p></p><strong><strong>1.HttpClient</strong></strong><p><p>The Android SDK contains httpclient, which removes the HttpClient class library directly in the Android6.0 version, and if you still want to use it, the workaround is:</p></p> <ul> <ul> <li>If you are using eclipse, add Org.apache.http.legacy.jar to the Libs<br>This jar package is in: **sdk\platforms\android-23\optional directory (requires android download<br>SDK for 6.0)</li> <li>If you are using Android studio, then add the build.gradle in the appropriate module:</li> </ul> </ul><pre class="prettyprint"><pre class="prettyprint"><code class=" hljs matlab"> <span class="hljs-cell">{ useLibrary <span class="hljs-string">‘org.apache.http.legacy‘</span> }</span></code></pre></pre><strong><strong>GET request for HttpClient</strong></strong><p><p>First we use the Defaulthttpclient class to instantiate a httpclient and configure the default request Parameters:</p></p><pre class="prettyprint"><code class=" hljs cs"> <span class="hljs-comment"><span class="hljs-comment">//create httpclient</span></span> <span class="hljs-keyword"><span class="hljs-keyword">Private</span></span>HttpClient<span class="hljs-title"><span class="hljs-title">createhttpclient</span></span>() {httpparams mdefaulthttpparams =<span class="hljs-keyword"><span class="hljs-keyword">New</span></span>Basichttpparams ();<span class="hljs-comment"><span class="hljs-comment">//set Connection Timeout</span></span>Httpconnectionparams.setconnectiontimeout (mdefaulthttpparams,<span class="hljs-number"><span class="hljs-number">15000</span></span>);<span class="hljs-comment"><span class="hljs-comment">//set Request Timeout</span></span>Httpconnectionparams.setsotimeout (mdefaulthttpparams,<span class="hljs-number"><span class="hljs-number">15000</span></span>); Httpconnectionparams.settcpnodelay (mdefaulthttpparams,<span class="hljs-keyword"><span class="hljs-keyword">true</span></span>); Httpprotocolparams.setversion (mdefaulthttpparams, httpversion.http_1_1); Httpprotocolparams.setcontentcharset (mdefaulthttpparams, HTTP. utf_8);<span class="hljs-comment"><span class="hljs-comment">//continuous Handshake</span></span>Httpprotocolparams.setuseexpectcontinue (mdefaulthttpparams,<span class="hljs-keyword"><span class="hljs-keyword">true</span></span>); HttpClient mhttpclient =<span class="hljs-keyword"><span class="hljs-keyword">New</span></span>Defaulthttpclient (mdefaulthttpparams);<span class="hljs-keyword"><span class="hljs-keyword">return</span></span>mhttpclient; }</code></pre><p><p>next, Create HttpGet and httpclient, request the network and get httpresponse, and process the Httpresponse:</p></p><pre class="prettyprint"><code class=" hljs cs"> <span class="hljs-keyword"><span class="hljs-keyword">Private</span></span> <span class="hljs-keyword"><span class="hljs-keyword">void</span></span> <span class="hljs-title"><span class="hljs-title">Usehttpclientget</span></span>(String Url) {httpget Mhttpget =<span class="hljs-keyword"><span class="hljs-keyword">New</span></span>HttpGet (url); Mhttpget.addheader (<span class="hljs-string"><span class="hljs-string">"Connection"</span></span>,<span class="hljs-string"><span class="hljs-string">"keep-alive"</span></span>);<span class="hljs-keyword"><span class="hljs-keyword">Try</span></span>{HttpClient mhttpclient = createhttpclient (); HttpResponse mhttpresponse = Mhttpclient.execute (mhttpget); Httpentity mhttpentity = mhttpresponse.getentity ();<span class="hljs-keyword"><span class="hljs-keyword">int</span></span>Code = Mhttpresponse.getstatusline (). Getstatuscode ();<span class="hljs-keyword"><span class="hljs-keyword">if</span></span>(<span class="hljs-keyword"><span class="hljs-keyword">NULL</span></span>! = Mhttpentity) {inputstream Minputstream = mhttpentity.getcontent (); String respose = converstreamtostring (minputstream); LOG.I (<span class="hljs-string"><span class="hljs-string">"wangshu"</span></span>,<span class="hljs-string"><span class="hljs-string">"request Status code:"</span></span>+ code +<span class="hljs-string"><span class="hljs-string">"\ n request result: \ n"</span></span>+ respose); Minputstream.close (); } }<span class="hljs-keyword"><span class="hljs-keyword">Catch</span></span>(ioexception E) {e.printstacktrace (); } }</code></pre><p><p>The Converstreamtostring method converts the request result to a string type:</p></p><pre class="prettyprint"><pre class="prettyprint"><code class=" hljs cs"><span class="hljs-keyword">private</span><span class="hljs-title">converStreamToString</span><span class="hljs-keyword">is</span>) throws IOException { <span class="hljs-keyword">new</span> BufferedReader(<span class="hljs-keyword">new</span> InputStreamReader(<span class="hljs-keyword">is</span>)); <span class="hljs-keyword">new</span> StringBuffer(); <span class="hljs-keyword">null</span>; <span class="hljs-keyword">while</span><span class="hljs-keyword">null</span>) { <span class="hljs-string">"\n"</span>); } String respose = sb.toString(); <span class="hljs-keyword">return</span> respose; }</code></pre></pre><p><p>Finally we turn on thread access baidu:</p></p><pre class="prettyprint"><pre class="prettyprint"><code class=" hljs java"> <span class="hljs-keyword">new</span> Thread(<span class="hljs-keyword">new</span> Runnable() { <span class="hljs-annotation">@Override</span> <span class="hljs-keyword">public</span><span class="hljs-keyword">void</span><span class="hljs-title">run</span>() { useHttpClientGet(<span class="hljs-string">"http://www.baidu.com"</span>); } }).start();</code></pre></pre><p><p>The returned result of the request, the request status code is 200, the result is an HTML page, here only the partial HTML code is intercepted:<br></p></p><p><p>The parameters of the GET request are exposed to the url, which is somewhat inappropriate, and the length of the URL is limited: the length is within 2048 characters, and the URL length is not limited after HTTP 1.1. In general, Post can replace get, so let's take a look at Httpclient's post Request.</p></p><strong><strong>POST request for HttpClient</strong></strong><p><p>The POST request and get are similar to the parameters that need to be configured to be passed:</p></p><pre class="prettyprint"><code class=" hljs cs"> <span class="hljs-keyword"><span class="hljs-keyword">Private</span></span> <span class="hljs-keyword"><span class="hljs-keyword">void</span></span> <span class="hljs-title"><span class="hljs-title">Usehttpclientpost</span></span>(String Url) {httppost Mhttppost =<span class="hljs-keyword"><span class="hljs-keyword">New</span></span>HttpPost (url); Mhttppost.addheader (<span class="hljs-string"><span class="hljs-string">"Connection"</span></span>,<span class="hljs-string"><span class="hljs-string">"keep-alive"</span></span>);<span class="hljs-keyword"><span class="hljs-keyword">Try</span></span>{HttpClient mhttpclient = createhttpclient (); List<namevaluepair> Postparams =<span class="hljs-keyword"><span class="hljs-keyword">New</span></span>Arraylist<> ();<span class="hljs-comment"><span class="hljs-comment">//parameters to pass</span></span>Postparams.add (<span class="hljs-keyword"><span class="hljs-keyword">New</span></span>Basicnamevaluepair (<span class="hljs-string"><span class="hljs-string">"username"</span></span>,<span class="hljs-string"><span class="hljs-string">"moon"</span></span>)); Postparams.add (<span class="hljs-keyword"><span class="hljs-keyword">New</span></span>Basicnamevaluepair (<span class="hljs-string"><span class="hljs-string">"password"</span></span>,<span class="hljs-string"><span class="hljs-string">"123"</span></span>)); Mhttppost.setentity (<span class="hljs-keyword"><span class="hljs-keyword">New</span></span>Urlencodedformentity (postparams)); HttpResponse mhttpresponse = Mhttpclient.execute (mhttppost); Httpentity mhttpentity = mhttpresponse.getentity ();<span class="hljs-keyword"><span class="hljs-keyword">int</span></span>Code = Mhttpresponse.getstatusline (). Getstatuscode ();<span class="hljs-keyword"><span class="hljs-keyword">if</span></span>(<span class="hljs-keyword"><span class="hljs-keyword">NULL</span></span>! = Mhttpentity) {inputstream Minputstream = mhttpentity.getcontent (); String respose = converstreamtostring (minputstream); LOG.I (<span class="hljs-string"><span class="hljs-string">"wangshu"</span></span>,<span class="hljs-string"><span class="hljs-string">"request Status code:"</span></span>+ code +<span class="hljs-string"><span class="hljs-string">"\ n request result: \ n"</span></span>+ respose); Minputstream.close (); } }<span class="hljs-keyword"><span class="hljs-keyword">Catch</span></span>(ioexception E) {e.printstacktrace (); } }</code></pre><strong><strong>2.HttpURLConnection</strong></strong><p><p>There have been some annoying bugs in httpurlconnection before the Android 2.2 release. For example, when you call the close () method on a readable inputstream, it is possible to invalidate the connection Pool. Then our usual solution is to disable the connection pooling function directly:</p></p><pre class="prettyprint"><pre class="prettyprint"><code class=" hljs cs"><span class="hljs-keyword">private</span><span class="hljs-keyword">void</span><span class="hljs-title">disableConnectionReuseIfNecessary</span>() { <span class="hljs-comment">// 这是一个2.2版本之前的bug</span> <span class="hljs-keyword">if</span> (Integer.parseInt(Build.VERSION.SDK) < Build.VERSION_CODES.FROYO) { System.setProperty(<span class="hljs-string">"http.keepAlive"</span><span class="hljs-string">"false"</span>); }}</code></pre></pre><p><p>So the use of httpclient in Android 2.2 and previous versions is a good choice, while in Android 2.3 and later, HttpURLConnection is the best choice, its API is simple, small size, So it works well for Android Projects. Compression and caching mechanisms can effectively reduce network access to traffic, in terms of speed and power saving also played a big role. Also in Android 6.0 version, httpclient Library was removed, HttpURLConnection is our only choice Later.</p></p><strong><strong>POST request for HttpURLConnection</strong></strong><p><p>Because it will be httpurlconnection POST request that GET request will be, so I just cite the example of post<br>First we create a Urlconnmanager class and then provide the Gethttpurlconnection () method inside to configure the default parameters and return httpurlconnection:</p></p><pre class="prettyprint"><code class=" hljs cs"> <span class="hljs-keyword"><span class="hljs-keyword"></span> public</span> <span class="hljs-keyword"><span class="hljs-keyword">Static</span></span>HttpURLConnection<span class="hljs-title"><span class="hljs-title">gethttpurlconnection</span></span>(String Url) {httpurlconnection mhttpurlconnection=<span class="hljs-keyword"><span class="hljs-keyword">NULL</span></span>;<span class="hljs-keyword"><span class="hljs-keyword">Try</span></span>{URL murl=<span class="hljs-keyword"><span class="hljs-keyword">New</span></span>URL (url); mhttpurlconnection= (httpurlconnection) murl.openconnection ();<span class="hljs-comment"><span class="hljs-comment">//set link Timeout time</span></span>Mhttpurlconnection.setconnecttimeout (<span class="hljs-number"><span class="hljs-number">15000</span></span>);<span class="hljs-comment"><span class="hljs-comment">//set Read timeout time</span></span>Mhttpurlconnection.setreadtimeout (<span class="hljs-number"><span class="hljs-number">15000</span></span>);<span class="hljs-comment"><span class="hljs-comment">//set Request Parameters</span></span>Mhttpurlconnection.setrequestmethod (<span class="hljs-string"><span class="hljs-string">"POST"</span></span>);<span class="hljs-comment"><span class="hljs-comment">//add Header</span></span>Mhttpurlconnection.setrequestproperty (<span class="hljs-string"><span class="hljs-string">"Connection"</span></span>,<span class="hljs-string"><span class="hljs-string">"keep-alive"</span></span>);<span class="hljs-comment"><span class="hljs-comment">//receive Input Stream</span></span>Mhttpurlconnection.setdoinput (<span class="hljs-keyword"><span class="hljs-keyword">true</span></span>);<span class="hljs-comment"><span class="hljs-comment">//need to be turned on when passing parameters</span></span>Mhttpurlconnection.setdooutput (<span class="hljs-keyword"><span class="hljs-keyword">true</span></span>); }<span class="hljs-keyword"><span class="hljs-keyword">Catch</span></span>(ioexception E) {e.printstacktrace (); }<span class="hljs-keyword"><span class="hljs-keyword">return</span></span>mhttpurlconnection; }</code></pre><p><p>Because we are sending a post request, we write another postparams () method in the Urlconnmanager class to organize the request parameters and write the request parameters to the output stream:</p></p><pre class="prettyprint"><code class=" hljs avrasm">public static void Postparams (outputstream Output,list<namevaluepair>paramslist) throws Ioexception{StringBui Lder mstringbuilder=new StringBuilder ()<span class="hljs-comment"><span class="hljs-comment">;</span></span>For (namevaluepair Pair:paramslist) {if (! Textutils<span class="hljs-preprocessor"><span class="hljs-preprocessor">. IsEmpty</span></span>(mstringbuilder)) {mstringbuilder<span class="hljs-preprocessor"><span class="hljs-preprocessor">. Append</span></span>(<span class="hljs-string"><span class="hljs-string">"&"</span></span>)<span class="hljs-comment"><span class="hljs-comment">;</span></span>} Mstringbuilder<span class="hljs-preprocessor"><span class="hljs-preprocessor">. Append</span></span>(urlencoder<span class="hljs-preprocessor"><span class="hljs-preprocessor">. Encode</span></span>(pair<span class="hljs-preprocessor"><span class="hljs-preprocessor">. GetName</span></span>(),<span class="hljs-string"><span class="hljs-string">"UTF-8"</span></span>))<span class="hljs-comment"><span class="hljs-comment">;</span></span>Mstringbuilder<span class="hljs-preprocessor"><span class="hljs-preprocessor">. Append</span></span>(<span class="hljs-string"><span class="hljs-string">"="</span></span>)<span class="hljs-comment"><span class="hljs-comment">;</span></span>Mstringbuilder<span class="hljs-preprocessor"><span class="hljs-preprocessor">. Append</span></span>(urlencoder<span class="hljs-preprocessor"><span class="hljs-preprocessor">. Encode</span></span>(pair<span class="hljs-preprocessor"><span class="hljs-preprocessor">. GetValue</span></span>(),<span class="hljs-string"><span class="hljs-string">"UTF-8"</span></span>))<span class="hljs-comment"><span class="hljs-comment">;</span></span>} bufferedwriter writer=new bufferedwriter, new OutputStreamWriter (output,<span class="hljs-string"><span class="hljs-string">"UTF-8"</span></span>))<span class="hljs-comment"><span class="hljs-comment">;</span></span>Writer<span class="hljs-preprocessor"><span class="hljs-preprocessor">. Write</span></span>(mstringbuilder<span class="hljs-preprocessor"><span class="hljs-preprocessor">. toString</span></span>())<span class="hljs-comment"><span class="hljs-comment">;</span></span>Writer<span class="hljs-preprocessor"><span class="hljs-preprocessor">. Flush</span></span>()<span class="hljs-comment"><span class="hljs-comment">;</span></span>Writer<span class="hljs-preprocessor"><span class="hljs-preprocessor">. Close</span></span>()<span class="hljs-comment"><span class="hljs-comment">;</span></span>}</code></pre><p><p>Next we add the request parameters, call the Postparams () method to organize the requested parameters into the output stream to httpurlconnection, request the connection and process the returned results:</p></p><pre class="prettyprint"><code class=" hljs cs"> <span class="hljs-keyword"><span class="hljs-keyword">Private</span></span> <span class="hljs-keyword"><span class="hljs-keyword">void</span></span> <span class="hljs-title"><span class="hljs-title">Usehttpurlconnectionpost</span></span>(String Url) {inputstream Minputstream =<span class="hljs-keyword"><span class="hljs-keyword">NULL</span></span>; HttpURLConnection mhttpurlconnection = urlconnmanager.gethttpurlconnection (url);<span class="hljs-keyword"><span class="hljs-keyword">Try</span></span>{list<namevaluepair> Postparams =<span class="hljs-keyword"><span class="hljs-keyword">New</span></span>Arraylist<> ();<span class="hljs-comment"><span class="hljs-comment">//parameters to pass</span></span>Postparams.add (<span class="hljs-keyword"><span class="hljs-keyword">New</span></span>Basicnamevaluepair (<span class="hljs-string"><span class="hljs-string">"username"</span></span>,<span class="hljs-string"><span class="hljs-string">"moon"</span></span>)); Postparams.add (<span class="hljs-keyword"><span class="hljs-keyword">New</span></span>Basicnamevaluepair (<span class="hljs-string"><span class="hljs-string">"password"</span></span>,<span class="hljs-string"><span class="hljs-string">"123"</span></span>)); Urlconnmanager.postparams (mhttpurlconnection.getoutputstream (), postparams); Mhttpurlconnection.connect (); Minputstream = Mhttpurlconnection.getinputstream ();<span class="hljs-keyword"><span class="hljs-keyword">int</span></span>Code = Mhttpurlconnection.getresponsecode (); String respose = converstreamtostring (minputstream); LOG.I (<span class="hljs-string"><span class="hljs-string">"wangshu"</span></span>,<span class="hljs-string"><span class="hljs-string">"request Status code:"</span></span>+ code +<span class="hljs-string"><span class="hljs-string">"\ n request result: \ n"</span></span>+ respose); Minputstream.close (); }<span class="hljs-keyword"><span class="hljs-keyword">Catch</span></span>(ioexception E) {e.printstacktrace (); } }</code></pre><p><p>Finally open thread request Network:</p></p><pre class="prettyprint"><pre class="prettyprint"><code class=" hljs java"><span class="hljs-keyword">private</span><span class="hljs-keyword">void</span><span class="hljs-title">useHttpUrlConnectionGetThread</span>() { <span class="hljs-keyword">new</span> Thread(<span class="hljs-keyword">new</span> Runnable() { <span class="hljs-annotation">@Override</span> <span class="hljs-keyword">public</span><span class="hljs-keyword">void</span><span class="hljs-title">run</span>() { useHttpUrlConnectionPost(<span class="hljs-string">"http://www.baidu.com"</span>); } }).start(); }</code></pre></pre><p><p>Here we still ask baidu, see what will happen?<br></p></p><p><p>Minputstream = Mhttpurlconnection.getinputstream () This code error, unable to find the File. Open fiddler to analyze, do not understand the Fiddler and HTTP protocol principle, Please check the Android Network programming (a) HTTP protocol principle this Article.</p></p><p><p>Our request Message:<br></p></p><p><p>There seems to be no problem with the request message, then look at the response message:</p></p><p><p></p></p><p><p>Reported 504 error, read the response data error, for our request the server can not return the full response, the returned data is 0 bytes, so Mhttpurlconnection.getinputstream () also cannot read the input stream of the server Response. Of course this error is normal, Baidu has no reason to deal with our post Request.</p></p><p><p>GitHub Source Download</p></p> <p><p>Android Network programming (ii) HttpClient and HttpURLConnection</p></p></span>
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