Android Development uses get methods to request and send data to the server

Source: Internet
Author: User

#1. First use a new servlet to process the login request

The code is as follows. Only the Doget method is implemented

Package Com.wzw.servlet;import Java.io.ioexception;import Javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import javax.servlet.http.httpservletresponse;/** * Servlet Implementation class Loginservlet */public class LoginServlet           Extends HttpServlet {private static final long serialversionuid = 1L;        /** * @see httpservlet#httpservlet () */public Loginservlet () {super (); TODO auto-generated Constructor stub}/** * @see Httpservlet#doget (httpservletrequest request, HttpServletResponse R esponse) */protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {String username=request.getparameter ("username"); String password=request.getparameter ("password"); if (Username.equals ("admin") &&password.equals ("123456") {Response.getwriter (). println ("Success");} Else{response.getwriter (). println ("Failed");}} /** * @see Httpservlet#dopost(HttpServletRequest request, httpservletresponse response) */protected void DoPost (HttpServletRequest request, HttpServletResponse response) throws Servletexception, IOException {//TODO auto-generated method stub}}

#2. In the Android layout file, the layout is as follows, two input boxes and buttons

<linearlayout xmlns: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 ">    <edittext        android:layout_margintop=" 10DP "        android:layout_width=" Fill_parent "        android:layout_height= "wrap_content"        android:id= "@+id/et_username"        android:hint= "Please enter first name"/>    <edittext        android:layout_margintop= "10DP"        android:layout_width= "Fill_parent"        android: layout_height= "Wrap_content"        android:id= "@+id/et_password"        android:hint= "Please enter password"/>        <button android:layout_height= "Wrap_content"    android:layout_width= "wrap_content"    android:onclick= "DoGet"    android:text= "Get way Submit"/>    </LinearLayout>


Added a click event on the button. #3. In main_activity, implement the specific code

Package Com.wzw.submitdata;import Com.wzw.submitdata.utils.netutil;import Android.os.bundle;import Android.app.activity;import Android.view.menu;import Android.view.view;import Android.widget.EditText;import Android.widget.toast;public class Mainactivity extends Activity {private EditText etusername;private EditText Etpassword; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); etusername = (EditText) Findviewbyid (r.id.et_username); Etpassword = ( EditText) Findviewbyid (R.id.et_password);} public void doget (View v) {final string Username=etusername.gettext (). toString (); final String password= Etpassword.gettext (). toString (); New Thread (New Runnable () {@Overridepublic void Run () {//access network to be implemented in a child thread, using get to take data final String state=netutil.loginofget (username, password);//execution on the main thread runonuithread (new Runnable () {public void run () {// is to operate on the main thread, with the result Toast.maketext (mainactivity.this, State, 0). Show ();});}). Start ();}}


#4. Also create a new gadget class to access the network

Package Com.wzw.submitdata.utils;import Java.io.bytearrayoutputstream;import Java.io.inputstream;import Java.net.httpurlconnection;import Java.net.malformedurlexception;import Java.net.url;public class NetUtil {/** * Use get access to access the network * @param username * @param password * @return The server returns the result */public the static string Loginofget (String Username,stri ng password) {httpurlconnection conn=null;try {String data= "username=" +username+ "&password=" +password; URL url=new url ("Http://192.168.1.4:8080/AndroidServer/LoginServlet?") +data); conn= (httpurlconnection) url.openconnection (); Conn.setrequestmethod ("GET"); Conn.setconnecttimeout (10000) ; Conn.setreadtimeout (conn.connect); int Code=conn.getresponsecode (); if (code==200) {InputStream is= Conn.getinputstream (); String State=getstringfrominputstream (IS), return state;}} catch (Exception e) {e.printstacktrace ();} Finally{if (conn!=null) {conn.disconnect ();}} return null;} /** * Returns a string based on the input stream * @param is * @return * @throws Exception */private static string getStringFrominputstream (InputStream is) throws Exception{bytearrayoutputstream baos=new Bytearrayoutputstream (); byte[] Buff= New Byte[1024];int Len=-1;while ((Len=is.read (Buff))!=-1) {baos.write (buff, 0, Len);} Is.close (); String html=baos.tostring (); Baos.close (); return html;}}


This makes it possible to request data from 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.