HttpURLConnection and HttpClient in Android enable app to interact with PC data

Source: Internet
Author: User

Self-study Android these days very hard, but very satisfied, because whenever learning a little bit of knowledge will feel very happy, feel today is particularly meaningful, perhaps this is a kind of inexplicable love it.

The following is the difference between httpurlconnection and httpclient today, in fact, these 2 kinds of data can be client and server interaction, just httpclient package more complete.

Let's take a look at the case.

The first type of httpurlconnection access server:

Customer-side code:

  

 Packagecom.example.demo01;Importjava.io.IOException;ImportJava.io.OutputStream;ImportJava.io.PrintWriter;Importjava.io.UnsupportedEncodingException;Importjava.net.HttpURLConnection;Importjava.net.MalformedURLException;ImportJava.net.URL;ImportJava.net.URLEncoder;Importjava.util.ArrayList;Importjava.util.List;ImportOrg.apache.http.HttpResponse;ImportOrg.apache.http.HttpStatus;ImportOrg.apache.http.NameValuePair;Importorg.apache.http.client.ClientProtocolException;Importorg.apache.http.client.HttpClient;Importorg.apache.http.client.entity.UrlEncodedFormEntity;ImportOrg.apache.http.client.methods.HttpPost;Importorg.apache.http.impl.client.DefaultHttpClient;ImportOrg.apache.http.message.BasicNameValuePair;ImportOrg.apache.http.protocol.HTTP;Importorg.apache.http.util.EntityUtils;ImportAndroid.annotation.SuppressLint;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.os.StrictMode;ImportAndroid.util.Log;ImportAndroid.view.Menu;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button;ImportAndroid.widget.EditText;Importandroid.widget.Toast; @SuppressLint ("Newapi") Public classMainactivityextendsActivity {PrivateEditText Unametxt, Pwdtxt; PrivateButton loginbtn; Private StaticString Serverpath = "Http://tplovejava.xicp.net/uploadApp/HttpTestServlet"; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); //mobile phone installation to accessStrictmode.setthreadpolicy (NewStrictMode.ThreadPolicy.Builder (). Detectdiskreads (). Detectdiskwrites (). D Etectnetwork ()//or. Detectall () for all detectable problems. Penaltylog (). build ()); //mobile phone installation to accessStrictmode.setvmpolicy (NewStrictMode.VmPolicy.Builder (). Detectleakedsqlliteobjects (). Penaltylog ()          . Penaltydeath (). build ());        Setcontentview (R.layout.activity_main); Unametxt=(EditText) Findviewbyid (R.id.user); Pwdtxt=(EditText) Findviewbyid (R.ID.PASD); LOGINBTN=(Button) Findviewbyid (r.id.submit); Loginbtn.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {String uname=Unametxt.gettext (). toString (); String pwd=Pwdtxt.gettext (). toString (); //httpurlconnection processing server-side interaction with clients                Try{URL URL=NewURL (Serverpath); HttpURLConnection Conn=(HttpURLConnection) url.openconnection (); //Set InputConn.setdoinput (true); //Set OutputConn.setdooutput (true); //setting up the cacheConn.setusecaches (false); //Set PostConn.setrequestmethod ("POST"); OutputStream OS=Conn.getoutputstream (); PrintWriter PW=NewPrintWriter (OS,true); Pw.println (1245); //Return Response Success                    intResponsecode =Conn.getresponsecode ();                System.out.print (Responsecode); } Catch(malformedurlexception e) {e.printstacktrace (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace ();    }                            }        }); } @Override Public BooleanOncreateoptionsmenu (Menu menu) {//inflate the menu; This adds items to the action bar if it is present.getmenuinflater (). Inflate (R.menu.main, menu); return true; }     Publicstring Dealencode (String str) {string encode= ""; Try{encode= Urlencoder.encode (str, "Utf-8")); } Catch(unsupportedencodingexception e) {e.printstacktrace (); }        returnencode; }}        

The second kind of HttpClient

HttpClient client =Newdefaulthttpclient (); Try {                    //set up a parameter collectionlist<namevaluepair> params =NewArraylist<namevaluepair>(); Params.add (NewBasicnamevaluepair ("uname", uname)); Params.add (NewBasicnamevaluepair ("pwd", PWD)); //Post ConnectionHttpPost HttpPost =NewHttpPost (Serverpath); Httppost.setentity (Newurlencodedformentity (params, HTTP.                    Utf_8)); HttpResponse Response=Client.execute (HttpPost); if(Response.getstatusline (). Getstatuscode () = =HTTPSTATUS.SC_OK) {String str= Entityutils.tostring (Response.getentity (), "Utf-8"); LOG.I ("Info", str); }                } Catch(clientprotocolexception e) {e.printstacktrace (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }

Server:

protected voidDoPost (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {response.setcharacterencoding ("Utf-8"); PrintWriter PW=Response.getwriter (); String uname= Request.getparameter ("uname"); String pwd= Request.getparameter ("pwd"); /*InputStream is = Request.getinputstream ();        InputStreamReader ISR = new InputStreamReader (IS);        BufferedReader br = new BufferedReader (ISR); System.out.println (Br.readline ());*/        if("Zs". Equals (uname) && "123". Equals (PWD) {Pw.print (Success); }Else{pw.print (Failed); }    }

 

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.