Android uses get mode to submit data to the server

Source: Internet
Author: User

First build a mock Web server, create a new Dynamic Web project, and the servlet code is as follows:

 PackageCom.wuyudong.web;Importjava.io.IOException;Importjavax.servlet.ServletException;ImportJavax.servlet.annotation.WebServlet;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;ImportOrg.apache.catalina.User;/*** Servlet Implementation class Loginservlet*/@WebServlet ("/loginservlet") Public classLoginservletextendsHttpServlet {Private Static Final LongSerialversionuid = 1L; /**     * @seeHttpservlet#doget (httpservletrequest request, HttpServletResponse * response)*/    protected voiddoget (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {String username= Request.getparameter ("username"); String Password= Request.getparameter ("Password"); System.out.println ("User name:" +username); System.out.println ("User name:" +password); if("Wuyudong". Equals (username) && "123". Equals (password)) {Response.getoutputstream (). Write ("Login Success". GetBytes ()); } Else{response.getoutputstream (). Write ("Login Failed". GetBytes ()); }    }    /**     * @seeHttpservlet#dopost (httpservletrequest request, HttpServletResponse * response)*/    protected voidDoPost (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {//TODO auto-generated Method Stub    }}

Create a new JSP page

<%@ Page Language="Java"ContentType="text/html; Charset=utf-8"pageencoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd "><HTML><Head><Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8"><title>Login Page</title></Head><Body>    <formAction= "Loginservlet"Method= "Get">User name:<inputname= "username"type= "text"><BR>Password:<inputname= "Password"type= "Password"><BR> <inputtype= "Submit">    </form></Body></HTML>

New Android Project, page layout:

<LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Xmlns:tools= "Http://schemas.android.com/tools"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"android:orientation= "vertical"Tools:context=". Mainactivity " >    <EditTextAndroid:id= "@+id/et_name"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:hint= "Please enter user name"Android:inputtype= "text" />    <EditTextAndroid:id= "@+id/et_pwd"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:hint= "Please enter password"Android:inputtype= "Textpassword" />    <ButtonAndroid:onclick= "Login"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:text= "Login"        /></LinearLayout>

The code is as follows:

 Packagecom.wuyudong.loginclient;ImportJava.io.ByteArrayOutputStream;ImportJava.io.InputStream;Importjava.net.HttpURLConnection;ImportJava.net.URL;ImportAndroid.os.Bundle;Importandroid.app.Activity;Importandroid.text.Editable;Importandroid.text.TextUtils;ImportAndroid.view.Menu;ImportAndroid.view.View;ImportAndroid.widget.EditText;ImportAndroid.widget.Toast; Public classMainactivityextendsActivity {PrivateEditText Et_name; PrivateEditText et_pwd; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Et_name=(EditText) Findviewbyid (r.id.et_name); Et_pwd=(EditText) Findviewbyid (R.ID.ET_PWD); }     Public voidLogin (view view) {String name=Et_name.gettext (). toString (). Trim (); String pwd=Et_pwd.gettext (). toString (). Trim (); if(Textutils.isempty (name) | |Textutils.isempty (PWD)) {Toast.maketext ( This, "User name password cannot be empty", 0). Show (); } Else {            //impersonate an HTTP request, submit data to the serverString Path = "Http://169.254.168.71:8080/web/LoginServlet?username=" + name + "&password=" +pwd; Try{URL URL=NewURL (path); //2. Establish an HTTP connectionHttpURLConnection conn =(httpurlconnection) URL. OpenConnection (); //3. Set up some request methodsConn.setrequestmethod ("GET");//Note get word captions must be capitalizedConn.setrequestproperty ("User-agent",                        "mozilla/5.0 (Windows NT 6.1; WOW64) applewebkit/537.36 (khtml, like Gecko) chrome/45.0.2454.101 safari/537.36 "); intCode = Conn.getresponsecode ();//the server's response code is OK//404 Page Not Found// //503 Server Internal Error                if(Code = = 200) {InputStream is=Conn.getinputstream (); //Convert the content of is to a stringBytearrayoutputstream BOS =NewBytearrayoutputstream (); byte[] buffer =New byte[1024]; intLen =-1;  while(len = is.read (buffer))! =-1) {bos.write (buffer,0, Len); The String result=NewString (Bos.tobytearray ());                    Is.close (); Toast.maketext ( This, result, 0). Show (); } Else{Toast.maketext ( This, "request failed, reason for failure:" + code, 0). Show (); }            } Catch(Exception e) {e.printstacktrace (); Toast.maketext ( This, "The request failed, please check the Logcat log console", 0). Show (); }        }    }}

Add Permission: Android.permission.INTERNET

Error when clicking the button after running the project:

06-18 21:08:16.237:w/system.err (7417): android.os.NetworkOnMainThreadException

Android forcibly lets 4.0 later versions do not check the main thread to access the network.

Workaround, add the following code to the OnCreate:

Strictmode.threadpolicy policy=new StrictMode.ThreadPolicy.Builder (). Permitall (). build ();
Strictmode.setthreadpolicy (Policy);

Get

Android uses get mode to submit data to the server

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.