Android Network programming uses HttpClient to access Web sites

Source: Internet
Author: User

Httpclientdemo.java interface is a two-button and a text box

/* * Use Httpclientlai to access submit request, receive response * A, send GET request * 1, create HttpClient object; HttpClient httpclient=new defaulthttpclient (); * 2, send GET request, create HttpGet object: HttpGet httpget=new httpget ("http://www.baidu.com"); * 3, the HttpGet object implemented with HttpClient object will get the object HttpResponse the server response object, the response is encapsulated in HttpResponse: * HttpResponse httpresponse= Httpclient.execute (HttpGet);  * 4, Get HTTP instance httpentity entity=httpresponse.getentity () from HttpResponse response;   * */public class Httpclientdemo extends Activity {TextView response;   Declares the HttpClient object HttpClient HttpClient; Handler handler=new Handler () {public void Handlemessage (Message msg) {if (msg.what==0x123) {///Use response to display the response of the server Respo  Nse.append (msg.obj.toString () + "\ n");    }  }   };        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (r.layout.activity_http_client);        1, create Defaulthttpclient object, interface callback HttpClient is an interface httpclient=new defaulthttpclient ();  Response= (TextView) Findviewbyid (r.id.response);  }/* * Send a GET request process to the service * * */public void Accesssecret (View v) {response.settext (""); Click the button to open the thread, send a GET request in the process new thread () {public void run () {//2, create a HttpGet object HttpGet httpget=new httpget ("http:/ /localhost:8080/foo/secret.jsp ");//jsp deployed on to cat server try {//3, HttpGet object with HttpClient object will get the object HttpResponse the server response object,    The response is encapsulated in the HttpResponse HttpResponse Httpresponse=httpclient.execute (httpget);    4, obtain the HTTP instance httpentity entity=httpresponse.getentity () from the HttpResponse response; The IF (entity!=null) {//5,entity instance obtains the content, establishes the input stream, reads the server content BufferedReader br=new BufferedReader (The new InputStreamReader (entity    . GetContent ()));    String Line=null;    while ((Line=br.readline ())!=null) {//loop reads the content from the input stream message msg=new message ();    msg.what=0x123;        Msg.obj=line; Handler.sendmessage (msg);//Send UI thread update UI component}}} catch (Clientprotocolexception e) {//TODO auto-generated catch Blo Cke.printstacktrace ();} catch (IOException e) {//TODO auto-generated catch blockE.printstacktrace ();}    }}.start (); */* * Send POST Request Flow * * * */public void Showlogin (View v) {Final view logindialog=getlayoutinflate   R (). Inflate (r.layout.login, NULL); New Alertdialog.builder (Httpclientdemo.this). Settitle ("Login System"). Setview (Logindialog). Setpositivebutton ( OK, new Dialoginterface.onclicklistener () {@Overridepublic void OnClick (dialoginterface dialog, int which) {// Gets the user name and password for the dialog box, final string name= ((EditText) Logindialog.findviewbyid (R.id.name)). GetText (). toString (); final string Pass= ((EditText) Logindialog.findviewbyid (R.id.pass)). GetText (). toString ();//Click OK to open the thread and send the POST request new thread () { public void Run () {try {//2, create HttpPost object HttpPost httppost=new httppost ("http://localhost:8080/foo/login.jsp");// JSP deployment on the to Cat server//3, the passed parameters are encapsulated, Namevaluepair is a simple name value to the node type list<namevaluepair> params=new arraylist< Namevaluepair> ();p Arams.add (New Basicnamevaluepair ("name", name)),//Add parameter Params.add (new Basicnamevaluepair (" Pass ", p);//3, set the encoding httppost.setentity (new Urlencodedformentity (params,http). Utf_8));//4,httpclient Object executes HttpPost request, obtains corresponding HttpResponse httpresponse=httpclient.execute (httppost);//5, If the status code is 200, the server succeeds in the appropriate if (Httpresponse.getstatusline (). Getstatuscode () ==200) {//200: Response succeeded, 301/302: Redirect, 404:not Found the resource was not found, the 501 server encountered an error that made it unable to service the request string msg = Entityutils.tostring (httpresponse.getentity ()); Looper.prepare ();//Prompt Login Success Toast.maketext (Httpclientdemo.this, MSG, Toast.length_long). Show (); Looper.loop ();}} catch (ParseException e) {//Todo auto-generated catch Blocke.printstacktrace ();} catch (IOException e) {//Todo Auto-gene Rated catch Blocke.printstacktrace ();}}.       Start ();}    }). Setnegativebutton ("Cancel", null). Show (); }



Android Network programming uses HttpClient to access Web sites

Related Article

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.