Android Learning II: HTTP operation

Source: Internet
Author: User

1. Initial knowledge of HTTP

HTTP (Hypertext Transfer Protocol Hypertext Transfer Protocol) is a network application layer protocol, based on TCP/IP, HTTP uses a reliable TCP connection, the default port is 80.

The more common HTTP is get and post, except that get is queried by setting parameters in the request URL, and post is sending the data to the Web side as a form

HTTP operation under 2.Android

 PackageOrg.tonny.httpUtil;Importjava.util.List;Importorg.apache.http.HttpEntity;ImportOrg.apache.http.HttpResponse;ImportOrg.apache.http.NameValuePair;Importorg.apache.http.client.HttpClient;Importorg.apache.http.client.entity.UrlEncodedFormEntity;ImportOrg.apache.http.client.methods.HttpGet;ImportOrg.apache.http.client.methods.HttpPost;Importorg.apache.http.impl.client.DefaultHttpClient;Importorg.apache.http.util.EntityUtils; Public classHttpservice {PrivateHttpClient _httpclient =NULL; PrivateHttpGet _httpget =NULL; PrivateHttpPost _httppost =NULL; PrivateHttpResponse _httpresponse =NULL; PrivateHttpentity _responseentity =NULL; PrivateHttpentity _requestentity =NULL;  PublicHttpservice () {_httpclient=Newdefaulthttpclient (); }     PublicString get (string url)throwsException {//HTTP Request Object_httpget =Newhttpget (URL); //perform a GET request_httpresponse =_httpclient.execute (_httpget); //200 indicates successful request        if(_httpresponse.getstatusline (). Getstatuscode () = = 200) {_responseentity=_httpresponse.getentity (); returnentityutils.tostring (_responseentity); } Else {            return NULL; }    }    /**     *      * @paramURL * Requested URL address *@paramparams * Post parameters, using key-value pairs to pass in the way *@return     * @throwsException*/     PublicString post (string url, list<namevaluepair> params)throwsException {_httppost=Newhttppost (URL); //Note that this requires a request entity_requestentity =Newurlencodedformentity (params);        _httppost.setentity (_requestentity); _httpresponse=_httpclient.execute (_httppost); if(_httpresponse.getstatusline (). Getstatuscode () = = 200) {                        //whether the data returns or uses the entity_responseentity =_httpresponse.getentity (); returnentityutils.tostring (_responseentity); } Else {            return NULL; }    }}

This encapsulates the post and get requests, where only the returned characters are processed, and the byte form (slice file) needs to be modified.

 Packageorg.tonnny.httptest;Importjava.util.ArrayList;Importjava.util.List;ImportOrg.apache.http.NameValuePair;ImportOrg.apache.http.message.BasicNameValuePair;ImportOrg.tonny.httpUtil.HttpService;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.os.Message;ImportAndroid.util.Log;ImportAndroid.view.View;ImportAndroid.widget.EditText;ImportAndroid.widget.TextView;Importandroid.app.Activity; Public classMainactivityextendsActivity {PrivateEditText _txturl =NULL; PrivateTextView _lblinfo =NULL; PrivateHandler _handler =NULL; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main);  This. _txturl = (EditText) This. Findviewbyid (R.id.txturl);  This. _lblinfo = (TextView) This. Findviewbyid (R.id.lblinfo); //here, we use handler to implement the communication between the work thread and the UI thread, mainly by working threads sending messages to the UI, so here's how to handle the message.         This. _handler =NewHandler () {@Override Public voidhandlemessage (Message msg) {String content=string.valueof (msg.obj); LOG.D ("Main in UI", content);            _lblinfo.settext (content);    }        }; }    /*** There is no way to define classes, but to define the onclick attribute directly in Activity_main to implement *@paramv*/     Public voidOnbtngetclick (View v) {//String url = this._txturl.gettext (). toString (). Trim ();String url = "Http://www.baidu.com"; GetThread Work=Newgetthread (URL);    Work.start (); }    /*** Here the post parameters need to be set well *@paramv*/     Public voidOnbtnpostclick (View v) {//String url = this._txturl.gettext (). toString (). Trim ();String url = "http://mail.163.com/"; List<NameValuePair> params =NewArraylist<namevaluepair>(); Params.add (NewBasicnamevaluepair ("Savelogin", "0")); Params.add (NewBasicnamevaluepair ("Url2",                "Http://mail.163.com/errorpage/error163.htm")); Params.add (NewBasicnamevaluepair ("username", "* * *")); Params.add (NewBasicnamevaluepair ("PASSOWRD", "* * *")); Postthread Work=Newpostthread (URL, params);    Work.start (); }    /*** Get Work thread class *@authortinny Cheung **/    Private Final classGetThreadextendsThread {PrivateString _url;  Publicgetthread (String url) {_url=URL; } @Override Public voidrun () {Httpservice GetMethod=NewHttpservice (); Try{String res=Getmethod.get (_url); Message msg=_handler.obtainmessage (); Msg.obj=Res;            _handler.sendmessage (msg); } Catch(Exception e) {e.printstacktrace (); }        }    }    /*** Post Work thread class *@authortinny Cheung **/    Private Final classPostthreadextendsThread {PrivateString _url; PrivateList<namevaluepair>_params;  PublicPostthread (String URL, list<namevaluepair>params) {_url=URL; _params=params; } @Override Public voidrun () {Httpservice Postmethod=NewHttpservice (); Try{String res=postmethod.post (_url, _params); Message msg=_handler.obtainmessage (); Msg.obj=Res;            _handler.sendmessage (msg); } Catch(Exception e) {e.printstacktrace (); }        }    }}

This implementation of the above encapsulation class use, because the mailbox involves personal privacy issues, so did not write up. Readers can obtain relevant data through simple analysis of tools such as HTTP Analyzer.

In addition, this design uses the communication between the threads, using the Loop-handler method to achieve, the specific details of the code has been reflected. Finally, remember to add a license to the list file as follows:

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

3. Summary

Personally think that the future of the project HTTP operation is certainly more, and the specific business combination, that is still quite complex, this piece is to focus on mastering, more learning and more practice. Things to do well and there is a great need for the next kung Fu, ah, I am such a lazy person, and then perfect it.

Android Learning II: HTTP operation

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.