1, server backstage use servlet development, here no longer introduced.
2, the network development do not forget to add access to the network in the configuration file permissions
<uses-permission android:name= "Android.permission.INTERNET"/>
3, network requests, processing can not be carried out in the main thread, must be in the sub-thread. Because the network request generally has about 1-3 seconds of delay, in the main thread to cause the main thread of the pause, the user experience is fatal. (The main thread should be only UI-drawn, such as network requests, resource downloads, and various time-consuming operations should be placed in child threads).
4.
Public classGetactivityextendsActivity {PrivateTextView mtvmsg; PrivateString result; @Overrideprotected voidonCreate (Bundle savedinstancestate) {//TODO auto-generated Method Stubrequestwindowfeature (Window.feature_no_title); Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_get); Initview (); } Private voidInitview () {mtvmsg=(TextView) Findviewbyid (r.id.tv_servlet_msg); NewThread (GetThread). Start (); } PrivateThread GetThread =NewThread () { Public voidrun () {httpurlconnection connection=NULL; Try{URL URL=NewURL ("Http://192.168.23.1:8080/TestProject/GetTest"); Connection=(HttpURLConnection) url.openconnection (); //set the request method, default is GetConnection.setrequestmethod ("GET"); //Set character setsConnection.setrequestproperty ("Charset", "UTF-8"); //Set File typeConnection.setrequestproperty ("Content-type", "text/xml; Charset=utf-8 "); //sets the request parameters, which can be obtained through the servlet's GetHeader ()Connection.setrequestproperty ("Cookie", "appname=" + urlencoder.encode ("Hello", "UTF-8")); //Setting Custom ParametersConnection.setrequestproperty ("MyProperty", "This is me!"); if(Connection.getresponsecode () = = 200) {InputStream is=Connection.getinputstream (); Result=stringstreamutil.inputstreamtostring (IS); Message msg=Message.obtain (); Msg.what= 0; Gethandler.sendmessage (msg); } } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } finally { if(Connection! =NULL) {connection.disconnect (); } } }; }; PrivateHandler GetHandler =NewHandler () { Public voidhandlemessage (android.os.Message msg) {if(Msg.what = = 0 && result!=NULL) {Mtvmsg.settext (result); } }; };}
5.
6, request parameters can be encoded by Urlencoder.encode ("Hello", "UTF-8"), Urldecoder.decode ("", "UTF-8") to decode. Here Urlencoder encodes the equal sign "=", so you can only encode the parameter multiple times.
7, here can pass Connection.setrequestproperty ("MyProperty", "This is me!") For parameter passing, this parameter is obtained through the servlet's GetHeader (). I think its security should be more secure than stitching it directly to the URL.
HttpURLConnection of Android network programming--get request