Android Network request

Source: Internet
Author: User

HTTP requests and Responses

HTTP request Packet Structure

Cases:

Post/meme.php/home/user/login http/1.1    114.215.86.90    cache-control:no-cache    Postman-token:bd243d6b-da03-902f-0a2c-8e9377f6f6ed    Content-type:application/x-www-form-  urlencoded    Tel=13637829200&password=123456

HTTP response Packet Structure

Cases:

http/1.1 13:20:55 GMT    server:apache/2.4.6 (CentOS) php/5.6.14 x
        c4>-powered-by:php/5.6.14    Content-length:78    Keep-alive:timeout=5, max=100     Connection:keep-Alive    Content-type:application/json; charset=utf-8    {" Status ": 202," info ":" \u6b64\u7528\u6237\u4e0d\u5b58\u5728\uff01 "," data ":null}

HTTP request mode

Commonly used are post and get

Get mode

Fill in the parameters in the URL:http://xxxx.xx.com/xx.php?params1=value1&params2=value2

Post mode

The parameters are encoded in the request body. The encoding is included x-www-form-urlencoded with the form-data .

x-www-form-urlencodedis encoded in this way: tel=13637829200&password=123456

form-datais encoded in this way:

----WEBKITFORMBOUNDARY7MA4YWXKTRZU0GW  Content-disposition:form-data; name= "Tel"  13637829200  ----WEBKITFORMBOUNDARY7MA4YWXKTRZU0GW  Content-disposition:form-data; name= "Password"  123456  ----WEBKITFORMBOUNDARY7MA4YWXKTRZU0GW

x-www-form-urlencodedCan only pass the key value pair, form-data may pass the binary system

HttpClient & HttpURLConnection

HttpClient has been abandoned.

The use of HttpURLConnection

 Public classNetUtils { Public Staticstring post (string URL, string content) {HttpURLConnection conn=NULL; Try {                //Create a URL objectURL Murl =Newurl (URL); //Call the OpenConnection () method of the URL to get the HttpURLConnection objectconn =(HttpURLConnection) murl.openconnection (); Conn.setrequestmethod ("POST");//set the request method to postConn.setreadtimeout (5000);//set read timeout to 5 secondsConn.setconnecttimeout (10000);//Set the connection network timeout to 10 secondsConn.setdooutput (true);//set this method to allow content to be output to the server//parameters for the POST requestString data =content; //get an output stream to write data to the server, by default, the system does not allow the output of content to the serverOutputStream out = Conn.getoutputstream ();//get an output stream to write data to the serverOut.write (Data.getbytes ());                Out.flush ();                Out.close (); intResponsecode = Conn.getresponsecode ();//Calling this method eliminates the need to use the Conn.connect () method                if(Responsecode = = 200) {InputStream is=Conn.getinputstream (); String Response=Getstringfrominputstream (IS); returnresponse; } Else {                    Throw NewNetworkerrorexception ("Response status is" +responsecode); }            } Catch(Exception e) {e.printstacktrace (); } finally {                if(Conn! =NULL) {conn.disconnect ();//Close Connection                }            }            return NULL; }         Public Staticstring get (string url) {HttpURLConnection conn=NULL; Try {                //building a URL object with a string URLURL Murl =Newurl (URL); Conn=(HttpURLConnection) murl.openconnection (); Conn.setrequestmethod ("GET"); Conn.setreadtimeout (5000); Conn.setconnecttimeout (10000); intResponsecode =Conn.getresponsecode (); if(Responsecode = = 200) {InputStream is=Conn.getinputstream (); String Response=Getstringfrominputstream (IS); returnresponse; } Else {                    Throw NewNetworkerrorexception ("Response status is" +responsecode); }            } Catch(Exception e) {e.printstacktrace (); } finally {                if(Conn! =NULL) {conn.disconnect (); }            }            return NULL; }        Private StaticString Getstringfrominputstream (InputStream is)throwsIOException {bytearrayoutputstream os=NewBytearrayoutputstream (); //The template code must be skilled            byte[] buffer =New byte[1024]; intLen =-1;  while(len = is.read (buffer))! =-1) {os.write (buffer,0, Len);            } is.close (); String State= Os.tostring ();//converts the data in a stream into a string, using the encoding utf-8 (the emulator default encoding)Os.close (); returnState ; }    }

To add Network permissions:<uses-permission android:name="android.permission.INTERNET"/>

Synchronous & Asynchronous

Async mode:

//in the main thread new handler, the main thread will be processed later.     PrivateHandler Handler =NewHandler (); PrivateTextView TextView; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); TextView=(TextView) Findviewbyid (R.id.text); NewThread (NewRunnable () {@Override Public voidrun () {//getting data from the network                FinalString response = Netutils.get ("http://www.baidu.com"); //sending processing operations to handlerHandler.post (NewRunnable () {@Override Public voidrun () {//updating the UI on the UI threadTextview.settext (response);            }                });    }}). Start (); }

Reference: http://www.jianshu.com/p/3141d4e46240

Android Network request

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.