Android uses HTTP protocol to access network--httpclient

Source: Internet
Author: User

Routine article

1.HttpClient is an interface that cannot create an instance of it, and typically creates an instance of Defaulthttpclient

HttpClient httpclient=New defaulthttpclient ();

2. If you want to initiate a GET request , create a HttpGet object, pass in the object of the target network, and then call the Excute () method in Htttpclient:

HttpGet httpget=New httpget ("http://www.baidu.com"); HttpResponse HttpResponse=httpclient.execute (httpget);

If you want to initiate a POST request that is more complex than get, first create a HttpPost object and pass in the destination URL

HttpPost httppost=New httppost ("http/:www.baidu.com");

The Namevaluepair collection is then held to hold the data to be submitted, and this parameter is passed into a urlencodedformentity, Then call HttpPost's Setentity () method to build the Urlencodedformentity incoming

list<namevaluepair> params=New arraylist<namevaluepair>();p arams.add (New Basicnamevaluepair ("username", "admin"));p Arams.add (new basicnamevaluepair ("Password", "123456" )); urlencodeformentity Entity=new urlencodeformentity (params, "utf-8"); httppost.setentity (entity) ;

The next is the same as the Get method, Httpclient.execute (HttpPost);

3. After executing the Execute () method, a HttpResponse object is returned, and the data returned by the server is inside, usually we remove the status code returned by the server, and if it equals 200, the request response is successful.

if (Httpresponse.getstatusline (). Getstatuecode () ==200) {  // Request and Response succeeded }

4. Read the specific content returned by the server, you can call GetEntity () access to a httpentity instance, and then call entityutils.tostring () this static class to convert Httpentity to a string

Httpentity entity=httpresponse.getentity ();

String response=entityutils.tostring (entity);

If the returned data is in Chinese, the character set must be specified as utf-8 when converting

String response=entityutils.tostring (Entity, "utf-8");

Real-Combat Chapter

Mainactivity

ImportAndroid.os.Handler;ImportAndroid.os.Message;Importandroid.support.v7.app.AppCompatActivity;ImportAndroid.os.Bundle;ImportAndroid.view.View;ImportAndroid.widget.Button;ImportAndroid.widget.TextView;Importorg.apache.http.HttpEntity;ImportOrg.apache.http.HttpResponse;Importorg.apache.http.client.HttpClient;ImportOrg.apache.http.client.methods.HttpGet;Importorg.apache.http.impl.client.DefaultHttpClient;Importorg.apache.http.util.EntityUtils; Public classMainactivityextendsAppcompatactivityImplementsview.onclicklistener{ Public Static Final intshow_response=0;//for update operations    PrivateButton Sendrequest_button; PrivateTextView responsetext; //handler for processing and sending messages    PrivateHandler handler=NewHandler () { Public voidhandlemessage (Message msg) {Switch(msg.what) { Caseshow_response:string RESPONSE=(String) msg.obj;            Responsetext.settext (response);    }        }    }; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Sendrequest_button=(Button) Findviewbyid (r.id.sendrequest); ResponseText=(TextView) Findviewbyid (R.id.response_text); Sendrequest_button.setonclicklistener ( This); } @Override Public voidOnClick (View v) {if(V.getid () = =r.id.sendrequest)        {sendrequestwithhttpclient (); }    }     Public voidsendrequestwithhttpclient () {NewThread (NewRunnable () {@Override Public voidrun () {Try{HttpClient HttpClient=Newdefaulthttpclient (); HttpGet HttpGet=NewHttpGet ("http://www.baidu.com"); HttpResponse HttpResponse=Httpclient.execute (HttpGet); if(Httpresponse.getstatusline (). Getstatuscode () ==200){                        //both the request and the response were successful.Httpentity entity=httpresponse.getentity (); String Response= Entityutils.tostring (Entity, "Utf-8"); Message Message=NewMessage (); Message.what=Show_response; //Save the results returned by the server to the messagemessage.obj=response.tostring ();                    Handler.sendmessage (message); }                }Catch(Exception e) {}finally{}}}). Start (); }}

Androidmanifest

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

Layout

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"android:orientation= "Vertical" > <Button Android:id= "@+id/sendrequest"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:text= "Send Request"/> <ScrollView android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content" > <TextView Android:id= "@+id/response_text"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"/> </ScrollView></LinearLayout>

Android uses HTTP protocol to access network--httpclient

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.