Httpurlconnection--get,post

Source: Internet
Author: User
Tags response code

Package com.ch.day4_httpurlconn;

Import Java.io.BufferedReader;
Import Java.io.DataOutputStream;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import java.net.HttpURLConnection;
Import java.net.MalformedURLException;
Import Java.net.URL;
Import java.util.ArrayList;
Import Java.util.Iterator;
Import Java.util.Vector;

Import Android.os.Bundle;
Import Android.os.Handler;
Import android.app.Activity;
Import Android.view.Menu;
Import Android.view.View;
Import Android.view.View.OnClickListener;
Import Android.widget.Button;
Import Android.widget.TextView;
Import Android.widget.Toast;

public class Mainactivity extends Activity {
Private TextView Jsondata;
Private Button login;
Server address, Path
public static final String Json_url = "Http://169.254.109.73:8080/tqyb/newsList.json";
public static final String Login_url = "Http://169.254.109.73:8080/serverof1407a/loginServlet";

An object that defines an anonymous inner class of handler
Handler Handler = new Handler () {
public void Handlemessage (Android.os.Message msg) {
if (msg.what = = 1) {
Jsondata.settext ((String) msg.obj);
}else if (msg.what = = 2) {
Login.settext ((String) msg.obj);
}
};
};

@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);

Init ();
}

public void init () {
Jsondata = (TextView) Findviewbyid (r.id.jsondata);
Login = (Button) Findviewbyid (R.id.login);
Click Login to server login verification
Login.setonclicklistener (New Onclicklistener () {
@Override
public void OnClick (View v) {
In the secondary thread, request the Web server
New Thread () {
public void Run () {
Call the GET request of HttpURLConnection to request JSON data from the server
String rs = loginbyserverbyget ("admin", "123456");

String rs = loginbyserverbypost ("Admin1", "123456");
In this thread, the data is passed to the main thread via handler, which is displayed in the component of the main thread
Handler.sendmessage (Handler.obtainmessage (2, RS));
if ("Success". Equals (RS)) {
Jump to the Features page,
}else{
Prompt Login failed, please modify login information and so on
}

};
}.start ();
}
});

Jsondata.setonclicklistener (New Onclicklistener () {
@Override
public void OnClick (View v) {
In the secondary thread, request the Web server
New Thread () {
public void Run () {
Call the GET request of HttpURLConnection to request JSON data from the server
String rs = Getjsonfromweb ();//This method requests the Web server
In this thread, the data is passed to the main thread via handler, which is displayed in the component of the main thread
Handler.sendmessage (Handler.obtainmessage (1, RS));
};
}.start ();
}
});
}
To the server to verify the login information, through the POST request
public string Loginbyserverbypost (string name,string Pass) {
String rs = "";
URL url = null;
HttpURLConnection urlconn = null;
BufferedReader br = null;
DataOutputStream output = null;
StringBuffer sb = new StringBuffer ();//define cache string, assemble string
try {

url = new URL (login_url);//Create and Server connection object URL
Urlconn = (httpurlconnection) url.openconnection ();//Open connection
Urlconn.setconnecttimeout (5*1000);//Set Connection timeout tolerance time
Urlconn.setreadtimeout (5*1000);//Set Read time

Set up a POST request
Urlconn.setrequestmethod ("POST");
Urlconn.setdoinput (TRUE);
Urlconn.setdooutput (TRUE);
Passing a value to the server via a POST request
Output = new DataOutputStream (Urlconn.getoutputstream ());//Create the server's export stream
String data = "Username=" +name+ "&userpass=" +pass;
Output.write (Data.getbytes ());
Output.flush ();
Output.close ();//Pass the value successfully, complete

if (urlconn.getresponsecode () = = 200) {//If the response code is 200 indicates a successful response, and the data is successfully
Get the appropriate data for the server, byte input stream (data stream), convert to cache character stream for easy reading
br = new BufferedReader (New InputStreamReader (Urlconn.getinputstream (), "Utf-8"));
rs = Br.readline ();//Get simple data returned by the server
System.out.println (RS);
}

} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}

Return rs;//converted to a string, returned
}
To the server to verify the login information, through the GET request
public string Loginbyserverbyget (string name,string Pass) {
String rs = "";
URL url = null;
HttpURLConnection urlconn = null;
BufferedReader br = null;
StringBuffer sb = new StringBuffer (login_url);//define cache string, assemble string
try {
Sb.append ("username=" +name);
Sb.append ("&userpass=" +pass);
System.out.println (Sb.tostring ());
url = new URL (sb.tostring ());//Create and Server connection object URL
Urlconn = (httpurlconnection) url.openconnection ();//Open connection
Urlconn.setconnecttimeout (5*1000);//Set Connection timeout tolerance time
Urlconn.setreadtimeout (5*1000);//Set Read time
if (urlconn.getresponsecode () = = 200) {//If the response code is 200 indicates a successful response, and the data is successfully
Get the appropriate data for the server, byte input stream (data stream), convert to cache character stream for easy reading
br = new BufferedReader (New InputStreamReader (Urlconn.getinputstream (), "Utf-8"));
rs = Br.readline ();//Get simple data returned by the server
System.out.println (RS);
}

} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}

Return rs;//converted to a string, returned
}


Public String Getjsonfromweb () {
URL url = null;
HttpURLConnection urlconn = null;
BufferedReader br = null;
StringBuffer sb = new StringBuffer ();//define cache string, assemble string
try {
url = new URL (json_url);//Create and Server connection object URL
Urlconn = (httpurlconnection) url.openconnection ();//Open connection
Urlconn.setconnecttimeout (5*1000);//Set Connection timeout tolerance time
Urlconn.setreadtimeout (5*1000);//Set Read time
if (urlconn.getresponsecode () = = 200) {//if the corresponding code is 200, the response is successful and the corresponding data is successfully
Get the appropriate data for the server, byte input stream (data stream), convert to cache character stream for easy reading
br = new BufferedReader (New InputStreamReader (Urlconn.getinputstream (), "Utf-8"));
String str = NULL;
while ((str = br.readline ()) = null) {//row of rows is read, a row is collected
Sb.append (str);
}
}

} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}

return sb.tostring ();//Convert to String, return
}

}

Httpurlconnection--get,post

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.