HttpURLConnection of Android network communication

Source: Internet
Author: User

The following example is a small example of a login server using HttpURLConnection.

Package Com.liang.logindemo;import Android.support.v7.app.actionbaractivity;import Android.os.bundle;import Android.view.menu;import Android.view.menuitem;import Android.view.view;import Android.widget.EditText;import Android.widget.toast;import Java.io.bufferedreader;import Java.io.inputstream;import Java.io.InputStreamReader; Import Java.io.outputstream;import Java.io.unsupportedencodingexception;import Java.net.httpurlconnection;import Java.net.malformedurlexception;import Java.net.url;import Java.net.urlconnection;import Java.net.URLEncoder;    public class Mainactivity extends Actionbaractivity {private EditText et_username;    Private EditText Et_password;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Et_username= (EditText) Findviewbyid (r.id.et_username);    Et_password= (EditText) Findviewbyid (R.id.et_password);       } public void Login (view view) { String Str=et_username.gettext (). toString ();        try {str=urlencoder.encode (str, "utf-8");        } catch (Unsupportedencodingexception e) {e.printstacktrace ();        } final String Username=str;        Final String Password=et_password.gettext (). toString ();                    Accessing the network new thread in a child thread (new Runnable () {@Override public void run () {try {                    Final Boolean issuccess =loginbypost (Username,password);                    Final Boolean issuccess = Loginbyget (Username,password);                        Use this method to notify the main thread without using handler, and the operation within the method is done by the main thread runonuithread (new Runnable () {@Override public void Run () {if (issuccess) {TOAST.M Aketext (Mainactivity.this, "Success!!!                            ", Toast.length_short). Show (); }else{Toast.maketext (Mainactivity.this, "lostDefeat!!!                            ", Toast.length_short). Show ();                }                        }                    });                } catch (Exception e) {e.printstacktrace ();    }}). Start ();     }/** * HttpURLConnection access server via GET request * @param Username,password * @return * @throws Exception * * Private Boolean loginbyget (string username,string password) throws exception{//server address String url= "http:/        /192.168.1.58:8080/login/servlet/login ";        String data= "? username=" +username + "&password=" +password;        HttpURLConnection Conn=null;        InputStream Is=null;        BufferedReader Reader=null;            try {//define a URL url murl=new url (url+data);            Open connection gets HttpURLConnection conn = (httpurlconnection) murl.openconnection ();            Set Request Mode Conn.setrequestmethod ("GET"); Set the access network timeout time, out of time will throw an exception conn.setconnecttimeout (5 *1000);            Set Read timeout time conn.setreadtimeout (3 * 1000);            Connection Network Conn.connect ();            Get the returned status code int code = Conn.getresponsecode ();                200 input stream for normal response if (code==200) {///get response content is = Conn.getinputstream ();                Read Content reader=new BufferedReader (new InputStreamReader (IS));                String state = Reader.readline ();                if ("SUCCESS". Equals (state)) {return true;                }else{return false;        }}} catch (Exception e) {throw e;            } finally {if (reader!=null) {reader.close ();            } if (Is!=null) {is.close ();        }//Close connection conn.disconnect ();    } return false;   /** *httpurlconnection Access server via POST request * @param userName * @param password * @return  * @throws Exception */boolean loginbypost (string username,string password) throws exception{String url= "        Http://192.168.1.58:8080/Login/servlet/Login ";        HttpURLConnection Conn=null;        InputStream Is=null;        BufferedReader Reader=null;        OutputStream OutputStream;        String data= "username=" +username+ "&password=" +password;            try {URL murl=new url (url);            conn = (httpurlconnection) murl.openconnection ();            Conn.setrequestmethod ("POST");            Conn.setconnecttimeout (5 * 1000);            Conn.setreadtimeout (3 * 1000);            setting allows the output stream to be opened by default, Conn.setdooutput (true) is not turned on;            Set the request header information, can set up multiple//conn.setrequestproperty (key,value);            Get the output stream for writing data to the server OutputStream = Conn.getoutputstream ();            Outputstream.write (Data.getbytes ());            Outputstream.flush ();            Outputstream.close ();            Conn.connect (); int code = Conn.getreSponsecode ();                if (code==200) {is = Conn.getinputstream ();                Reader=new BufferedReader (New InputStreamReader (IS));                String state = Reader.readline ();                if ("SUCCESS". Equals (state)) {return true;                }else{return false;        }}} catch (Exception e) {throw e;            } finally {if (reader!=null) {reader.close ();            } if (Is!=null) {is.close ();        } conn.disconnect ();    } return false; }}

Layout two input boxes a submit button, relatively simple, is not listed.

Note Adding network access permissions in the manifest file




HttpURLConnection of Android network communication

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.