Android Simple Get Server data

Source: Internet
Author: User

1, Activity_main.xml

<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= "Com.example.getserverdata.MainActivity" >    <EditTextAndroid:id= "@+id/et_username"Android:hint= "Please enter user name"Android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"         >    </EditText>    <EditTextAndroid:id= "@+id/et_password"Android:hint= "Please enter password"Android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"Android:ems= "Ten"Android:inputtype= "Textpassword" />    <ButtonAndroid:onclick= "click"Android:id= "@+id/button1"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:text= "Login" /></LinearLayout>

2.androidmanifest.xml Configuring Permissions

<?XML version= "1.0" encoding= "Utf-8"?><Manifestxmlns:android= "Http://schemas.android.com/apk/res/android" Package= "Com.example.getserverdata"Android:versioncode= "1"Android:versionname= "1.0" >    <USES-SDKandroid:minsdkversion= "8"android:targetsdkversion= "+" />    <uses-permissionAndroid:name= "Android.permission.INTERNET"/>    <ApplicationAndroid:allowbackup= "true"Android:icon= "@drawable/ic_launcher"Android:label= "@string/app_name"Android:theme= "@style/apptheme" >        <ActivityAndroid:name=". Mainactivity "Android:label= "@string/app_name" >            <Intent-filter>                <ActionAndroid:name= "Android.intent.action.MAIN" />                <categoryAndroid:name= "Android.intent.category.LAUNCHER" />            </Intent-filter>        </Activity>    </Application></Manifest>

3.get Request

 PackageCom.example.getserverdata.service;ImportJava.io.InputStream;Importjava.net.HttpURLConnection;ImportJava.net.URL;ImportCom.example.getserverdata.utils.StreamUtil; Public classLoginservice { Public Staticstring loginbyget (string username,string password) {string path= "Http://192.168.1.100:8088/Login.ashx?username=" +username+ "&password=" +password; Try {            //Create URLURL url =NewURL (path); //Create an HTTP connectionHttpURLConnection conn =(HttpURLConnection) url.openconnection (); //Setting the connection timeConn.setconnecttimeout (5000); //Set Request ModeConn.setrequestmethod ("GET"); //GET Request Code            intCode =Conn.getresponsecode (); System.out.println ("Code:" +code); if(code==200)            {                //Request succeeded//Get Response DataInputStream is =Conn.getinputstream (); //Get Response DataString result =Streamutil.readinputstream (IS); returnresult; }            Else            {                //request failed                return NULL; }                                } Catch(Exception e) {e.printstacktrace (); }                return NULL; }}

4. Convert InputStream to String

 Packagecom.example.getserverdata.utils;ImportJava.io.ByteArrayOutputStream;Importjava.io.IOException;ImportJava.io.InputStream; Public classStreamutil { Public StaticString Readinputstream (InputStream is) {Bytearrayoutputstream BAOs=NewBytearrayoutputstream (); byte[] data =New byte[1024]; intLen = 0; Try {             while(len = is.read (data))!=-1) baos.write (data,0, Len);            Is.close ();            Baos.close (); return NewString (Baos.tobytearray ()); } Catch(Exception e) {e.printstacktrace (); }                    return NULL; }}

5.MainActivity

 PackageCom.example.getserverdata;ImportCom.example.getserverdata.service.LoginService;ImportAndroid.os.Bundle;Importandroid.support.v7.app.ActionBarActivity;ImportAndroid.view.Menu;ImportAndroid.view.MenuItem;ImportAndroid.view.View;ImportAndroid.widget.EditText;ImportAndroid.widget.Toast; Public classMainactivityextendsactionbaractivity {PrivateEditText Et_username; PrivateEditText Et_password; @Overrideprotected voidonCreate (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 voidClick (View view) {FinalString username =Et_username.gettext (). toString (). Trim (); FinalString Password =Et_password.gettext (). toString (). Trim (); NewThread () { Public voidrun () {FinalString result =loginservice.loginbyget (username, password); System.out.println ("REUSLT:" +result); if(result!=NULL) {Runonuithread (NewRunnable () {@Override Public voidrun () {Toast.maketext (mainactivity. This, result, 0). Show ();                                    }                                                                    }); }                                Else{Runonuithread (NewRunnable () {@Override Public voidrun () {Toast.maketext (mainactivity. This, "Failed to get data", 0). Show ();                                    }                    });                    }}}.start (); }    }

Android Simple Get Server data

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.