Android uses HTTP protocol to access network--httpconnection

Source: Internet
Author: User

Routine article

Using Httpconnection to access the network generally has the following routines:

1. Obtain an instance of Httpconnection, new out a URL object, and pass in the destination URL, and then call the OpenConnection () method.

1 httpurlconnection connection=null; 2 URL url=new URL ("http://www.baidu.com"); 3 connection= (httpurlconnection) url.openconnection ();

2. After obtaining an instance of Httpconnection, the method used to set the request (get: Fetch data from the server, post: Submit data to the server)

Connection.setrequestmethod ("GET");
Connection.setrequestmethod ("POST");

3. Freely customizable links (set the connection timeout, the number of milliseconds to read, and the message the server wants to receive first Class)

Connection.setconnecttimeout (8000); Connection.setreadtimeout (8000);

4. Use the getInputStream () method to get the returned input stream of the server, and then read

InputStream In=connection.getinputstream ();//bottom face acquired input stream to read BufferedReader bufr=new BufferedReader (new InputStreamReader (in)); StringBuilder response=new StringBuilder (); String Line=null;while ((Line=bufr.readline ())!=null) {          response.append (line);}

5. Call the Disconnect () method to shut down the HTTP connection

if (connection!=null) {     connection.disconnect ();}

Real-Combat Chapter

Create a new Android project

1.activity_main.xml (with a button and a textview inside)

<?XML version= "1.0" encoding= "Utf-8"?><LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"android:orientation= "vertical">    <ButtonAndroid:id= "@+id/send_request"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:text= "Send Request" />    <ScrollViewAndroid:layout_width= "Match_parent"Android:layout_height= "Match_parent">        <TextViewAndroid:id= "@+id/response_text"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content" />    </ScrollView></LinearLayout>

2.MainActivity

ImportAndroid.os.Handler;ImportAndroid.os.Message;Importandroid.support.v7.app.AppCompatActivity;ImportAndroid.os.Bundle;ImportAndroid.view.View;ImportAndroid.widget.Button;ImportAndroid.widget.TextView;ImportJava.io.BufferedReader;ImportJava.io.InputStream;ImportJava.io.InputStreamReader;Importjava.net.HttpURLConnection;ImportJava.net.URL; Public classMainactivityextendsAppcompatactivityImplementsView.onclicklistener { Public Static Final intshow_response=0;//for update operations    PrivateButton SendRequest; PrivateTextView responsetext; //hander for processing and sending messages    PrivateHandler handler=NewHandler () { Public voidhandlemessage (Message msg) {//if the rebate is msg.what=show_response, the development action is made, if you want to do something else, the thread will show_response change in the Strand            Switch(msg.what) { Caseshow_response:string RESPONSE=(String) msg.obj; //perform UI actions to display the results to the interfaceResponsetext.settext (response);    }        }    }; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); SendRequest=(Button) Findviewbyid (r.id.send_request); ResponseText=(TextView) Findviewbyid (R.id.response_text); Sendrequest.setonclicklistener ( This); } @Override Public voidOnClick (View v) {if(V.getid () = =r.id.send_request)        {sendrequestwithhttpurlconnection (); }    }    Private voidsendrequestwithhttpurlconnection () {//turn on threads to initiate network requests        NewThread (NewRunnable () {@Override Public voidrun () {httpurlconnection connection=NULL; Try{URL URL=NewURL ("http://www.baidu.com"); Connection=(HttpURLConnection) url.openconnection (); Connection.setrequestmethod ("GET"); Connection.setconnecttimeout (8000); Connection.setreadtimeout (8000); InputStream in=Connection.getinputstream (); //The input stream to be read under the faceBufferedReader bufr=NewBufferedReader (NewInputStreamReader (in)); StringBuilder Response=NewStringBuilder (); String Line=NULL;  while((Line=bufr.readline ())! =NULL) {response.append (line); } Message Message=NewMessage (); Message.what=Show_response; //to store the data returned by the server in a messagemessage.obj=response.tostring ();                Handler.sendmessage (message); }Catch(Exception e) {e.printstacktrace (); }finally {                    if(connection!=NULL) {connection.disconnect ();    }}}). Start (); }}

Registering Permissions in 3.androidmanifest.xml

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

OK, this simple example is finished, and then look at the effect.

So we can see the data that the server returned to us.

Android uses the HTTP protocol to access the network--httpconnection

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.