04_android Introduction _ Use HttpURLConnection get way to achieve landing case

Source: Internet
Author: User

1. Overview

each HttpURLConnection instance can be used to generate a single request, but other instances can transparently share the underlying network connected to the HTTP server. The call to the close () method on HttpURLConnection's InputStream or outputstream after the request frees the network resources associated with this instance, but has no effect on the shared persistent connection . If the persistent connection is idle when calling disconnect () , the underlying socket may be closed .

2. In 03_android Introduction _ Use Relativelayout to achieve landing interface effect of the case to continue to improve the results as follows:


Click the login button to see the results in the console of the server


Before clicking on the login button, go through the Logcat tool in Eclipse and click


+ # Popup dialog box


Add the filtered name and filter the identity click OK to finish.

When you click the login button, you can see the results of the execution in Logcat


When you enter the wrong user name and password, you can see the following effect


3. The implementation of the specific loginactivity code is as follows: (Note: I added a detailed comment in the code please read it carefully)

Package Www.csdn.net.lesson03;import Java.io.bytearrayoutputstream;import Java.io.inputstream;import Java.net.httpurlconnection;import Java.net.url;import Java.net.urlencoder;import Android.app.Activity;import Android.os.bundle;import Android.text.textutils;import Android.view.view;import Android.widget.EditText;import Android.widget.toast;public class Loginactivity extends Activity {//Declare control object private EditText Et_name, et_pass;@ overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);// Sets the displayed view Setcontentview (r.layout.activity_login);//The control object that gets the user name through the Findviewbyid (id) method et_name = (EditText) Findviewbyid ( R.id.et_name);//The Control object Et_pass = (EditText) Findviewbyid (R.id.et_pass) that gets the user's password through the Findviewbyid (ID) method;} /** * by android:onclick= "Login" to specify the method that requires this method to accept you click on the control object's Parameters v * * @param v */public void login (View v) {//Get the Idint ID of the click Control = V.getid ();//How to handle the processing of the switch (ID) {//login event based on the ID) r.id.btn_login://get the user name final String userName = Et_name.gettext (). toString ();/Get user password final String userpass = Et_pass.gettext (). toString (); if (Textutils.isempty (userName) | | Textutils.isempty (Userpass)) {Toast.maketext (this, "username or password cannot be empty", Toast.length_long). Show ();} else { System.out.println ("----------------------send request to Server----------------------");//<span style= "color: #ff6666;" > Access network (requires a network of permissions) <uses-permission//android:name= "Android.permission.INTERNET"/></span>//<span style= "COLOR: #ff6666;" > Access Network (Time-consuming operation) Avoid blocking the main thread (UI) to open a new child thread to process </span>new thread () {public void run () {//Call Loginbyget method Loginbyget ( UserName, Userpass);};}. Start ();} Break;default:break;}} /** * Request sent by Get method * * @param userName * @param userpass */public void Loginbyget (String userName, String userpass) {try {//Set the requested address through Urlencoder.encode (string s, String enc)//Convert the string to application/x-www-form-urlencoded format using the specified encoding mechanism string Spec = "<span style=" color: #ff6666; " >http://172.16.237.200:8080/video/login.do</span>?username= "+ urlencoder.encode (username," UTF-8 ") +" &Amp;userpass= "+ urlencoder.encode (userpass," UTF-8 ");//Create URL object based on address (URL of network access) URL url = new URL (spec);// Url.openconnection () Open Network link httpurlconnection urlconnection = (httpurlconnection) url.openconnection (); Urlconnection.setrequestmethod ("GET");//The way the request is set Urlconnection.setreadtimeout (5000);// Set timeout time urlconnection.setconnecttimeout (5000);//Set the link timeout time//set the requested header Urlconnection.setrequestproperty ("User-agent", "mozilla/5.0 (Windows NT 6.3; WOW64; rv:27.0) gecko/20100101 firefox/27.0 ");//Get the status code of the response 404 505 302if (urlconnection.getresponsecode () = = 200) {//get the input stream of the response Object InputStream is = Urlconnection.getinputstream ();//create Byte output stream object Bytearrayoutputstream os = new Bytearrayoutputstream (); /define the length of the read int len = 0;//define buffer byte buffer[] = new byte[1024];//The buffer size, loop read while (len = is.read (buffer))! =-1) {//based on read The length of the Os.write is written to the OS object (buffer, 0, Len);} Release the resource Is.close (); Os.close ();//Returns a string of result = new String (Os.tobytearray ()); System.out.println ("***************" + result+ "******************");} else {SyStem.out.println ("------------------link failed-----------------");}} catch (Exception e) {e.printstacktrace ();}}}

4. Project manifest document (Androidmanifest.xml)

<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/        Android "package=" Www.csdn.net.lesson03 "android:versioncode=" 1 "android:versionname=" 1.0 "> <uses-sdk android:minsdkversion= "android:targetsdkversion="/> <!--Add permissions to access the network and <uses-permis Sion android:name= "Android.permission.INTERNET"/> <application android:allowbackup= "true" android:i con= "@drawable/ic_launcher" android:label= "@string/app_name" android:theme= "@style/apptheme" > &lt            Activity android:name= "www.csdn.net.lesson03.LoginActivity" android:label= "@string/app_name" > <intent-filter> <action android:name= "Android.intent.action.MAIN"/> & Lt;category android:name= "Android.intent.category.LAUNCHER"/> </intent-filter> &LT;/ACTIVITY&G    T </application></manifest> 

5. About the server I write only one servlet to handle the corresponding request processing

Package Www.csdn.net.servlet;import Java.io.ioexception;import Javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;public class Loginservlet extends HttpServlet {/** * */private static final long s Erialversionuid = 1l;protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {//Gets the parameter value of the request string userName = Request.getparameter ("UserName"); String Userpass = Request.getparameter ("Userpass"); System.out.println ("+username+"---"+userpass" before transcoding),//get method of request garbled processing userName = new String (Username.getbytes (" Iso8859-1 ")," UTF-8 "), Userpass = new String (userpass.getbytes (" iso8859-1 ")," UTF-8 "); System.out.println ("After transcoding---" +username+ "---" +userpass), if ("Qnovations". Equals (UserName) && "123". Equals ( Userpass)) {//Response login Success Information Response.getoutputstream (). Write ("Login successful". GetBytes ());} else{//the corresponding login failed information Response.getoutputstream (). Write ("Login failed". GetBytes ());}} protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { This.doget (request, Response);}}
The configuration of the corresponding Web. xml file is:

<?xml version= "1.0" encoding= "UTF-8"? ><web-app xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns= "Http://java.sun.com/xml/ns/javaee" xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee/http Java.sun.com/xml/ns/javaee/web-app_2_5.xsd "id=" webapp_id "version=" 2.5 ">  <display-name>video</ display-name>    <servlet>    <description></description>    <display-name> loginservlet</display-name>    <servlet-name>LoginServlet</servlet-name>    < servlet-class>www.csdn.net.servlet.loginservlet</servlet-class>  </servlet>    < servlet-mapping>    <servlet-name>LoginServlet</servlet-name>    <url-pattern>/login.do </url-pattern>  </servlet-mapping>  </web-app>

6. Frequent bug analysis on program students

6.1. Forget to add permission to access the network in the project manifest file.

  <!--add permissions to access the network--    <uses-permission android:name= "Android.permission.INTERNET"/>
Then the program will run with the following error


6.2. Call directly in the event handling of the button click

Loginbyget (UserName, Userpass);
method is not called in a child thread
Loginbyget (UserName, Userpass);
Method will appear the following bug


Bug Description: In the later version of android4.0 to send a request for a network, you must write this request in a sub-thread, or you will see a bug like the above

6.3. Place the requested address when sending a request to the network:

Http://172.16.237.200:8080/video/login.do
Was written

Http://localhost:8080/video/login.do or Http://127.0.0.1:8080/video/login.do

You will see the following bug:



After the understanding, ask the students to think about how to write the returned data in the location of the Nikki



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.