Android access network via Get and Post methods

Source: Internet
Author: User
Tags gettext readline

This demo demo shows that Android interacts with the server through get and POST request methods, so you need to build a server test that you can use Tomcat for reference: http://blog.csdn.net/youmingyu/article/ details/52524006, Demo: Download address.

Note Open Access network permissions: <uses-permission android:name= "Android.permission.INTERNET"/>


Source:

Package fk.androiddemo_007;
Import Android.os.Handler;
Import Android.os.Message;
Import android.support.v7.app.AppCompatActivity;
Import Android.os.Bundle;
Import Android.view.View;
Import Android.widget.Button;
Import Android.widget.EditText;

Import Android.widget.TextView;
Import Java.io.BufferedReader;
Import Java.io.DataOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import java.net.HttpURLConnection;
Import Java.net.URL;

Import Java.net.URLEncoder; Register <uses-permission android:name= "Android.permission.INTERNET"/> public class mainactivity in the manifest file
    Extends Appcompatactivity implements View.onclicklistener {EditText usertext,passwordtext,iptext;
    TextView ResText;
    Button postbut,getbut;
    String Name,password,ip;
    MyHandler handler;
        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);

   Setcontentview (R.layout.activity_main);     usertext= (EditText) Findviewbyid (R.id.usertext);
        passwordtext= (EditText) Findviewbyid (R.id.passwordtext);
        iptext= (EditText) Findviewbyid (R.id.iptext);

        restext= (TextView) Findviewbyid (R.id.restext);
        getbut= (Button) Findviewbyid (r.id.getbut);
        Getbut.setonclicklistener (this);
        postbut= (Button) Findviewbyid (r.id.postbut);

        Postbut.setonclicklistener (this);
    Handler=new MyHandler ();
        @Override public void OnClick (View v) {name=usertext.gettext (). toString (). Trim ();
        Password=passwordtext.gettext (). toString (). Trim ();

        Ip=iptext.gettext (). toString (). Trim ();

    if (v==getbut) new GetThread (). Start ();//Send Else New Postthread () with Get method. Start ()//Send by post method} Network thread because the main thread cannot access the intent class GetThread extends thread{public void run () {httpurlconnection conn= null;//declares the Connection object String urlstr= "http://" +ip+: 8080/example001.jsp?name= "+name+";p assword= "+password;
            InputStream is = null;
            String resultdata = ""; try {URL url = new URL (urlstr);//url Object conn = (httpurlconnection) url.openconnection (); /Use the URL to open a link, below set this connection Conn.setrequestmethod ("get"); Use GET request if (Conn.getresponsecode () ==200) {//Return 200 to indicate the connection success is = Conn.getinputstream ();
                    /Get input stream InputStreamReader ISR = new InputStreamReader (IS);
                    BufferedReader bufferreader = new BufferedReader (ISR);
                    String inputline = "";
                    while ((Inputline = Bufferreader.readline ())!= null) {Resultdata + = inputline + "\ n";
                    } System.out.println ("Get Method Fetch content:" +resultdata);
                Showres ("Get Method Fetch content:" + resultdata);
            } catch (IOException e) {e.printstacktrace ();
     }   } class Postthread extends thread{public void run () {httpurlconnection conn=null;
            String urlstr= "http://" +ip+ ": 8080/example001.jsp";
            InputStream is = null;
            String resultdata = ""; try {URL url = new URL (urlstr);//url Object conn = (httpurlconnection) url.openconnection (); /Use the URL to open a link, the following set up this connection Conn.setrequestmethod ("POST");
                    Using POST request//Parameter strings string param= "Name=" +urlencoder.encode (name, "UTF-8")/server does not recognize Chinese characters

                + "&password=" +urlencoder.encode (password, "UTF-8"); The output to the server to emit parameters, require characters, so can not be directly with Getoutputstream DataOutputStream dos=new dataoutputstream Conn.getoutputstream (
                ));
                Dos.writebytes (param);
                Dos.flush ();

                Dos.close ();   if (Conn.getresponsecode () ==200) {//return 200 means the corresponding success is = Conn.getinputstream (); //Gets the input stream inputstreamreader ISR = new InputStreamReader (IS);
                    BufferedReader bufferreader = new BufferedReader (ISR);
                    String inputline = "";
                    while ((Inputline = Bufferreader.readline ())!= null) {Resultdata + = inputline + "\ n";
                    System.out.println ("POST method Fetch content:" + resultdata);
                Showres ("POST method Fetch content:" + resultdata);
            } catch (IOException e) {e.printstacktrace ();
        ()}///For main thread send message public void Showres (String res) {Bundle bundle=new Bundle ();
        Bundle.putstring ("res", res),//bundle class object data message Msg=handler.obtainmessage () can also be placed in a serialized or encapsulated format;//Be retrieved every time you send it
        Msg.setdata (bundle); Handler.sendmessage (msg);//////handler to main thread with custom handler class class MyHandler extends Handler {@Overri
     De//Receive information from other threads and process   public void Handlemessage (message msg) {Bundle bundle=msg.getdata ();
        Restext.settext (Bundle.get ("res"). toString ());
 }
    }

}

Run Screenshots: Note that the box fills in the IP address of your own server



PS1:

Android can also use HttpClient with server interaction, but in the Android 6.0 (API 23) and beyond, Google has removed classes related to Apache httpclient, so if you want to continue using Apache HttpClient, you need to add the appropriate jar package, method reference: http://blog.csdn.net/youmingyu/article/details/52526997

Httpclient-4.5.2.jar: Download address, website download address: Address


PS2:

The difference between the Get method and the Post method is to intercept a picture of Mars teacher:



Related Article

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.