The Android platform submits information cases to web applications through get and post

Source: Internet
Author: User

Reference Book: crazy android Handouts

1. Display

2. UI layout <? Xml version = "1.0" encoding = "UTF-8"?>
<LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android"
Android: orientation = "vertical"
Android: layout_width = "fill_parent"
Android: layout_height = "fill_parent"
>
<LinearLayout
Android: orientation = "horizontal"
Android: layout_width = "fill_parent"
Android: layout_height = "wrap_content"
Android: gravity = "center"
>
<Button
Android: id = "@ + id/get"
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: text = "@ string/get"
/>
<Button
Android: id = "@ + id/post"
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: text = "@ string/post"
/>
</LinearLayout>
<EditText
Android: id = "@ + id/show"
Android: layout_width = "fill_parent"
Android: layout_height = "fill_parent"
Android: editable = "false"
Android: cursorVisible = "false"
Android: gravity = "top"
/>
</LinearLayout>

 

3. Modify the tool class for sending get and post requests as follows:
Public class GetPostUtil
{
/**
* Send a GET request to a specified URL
*
* @ Param url
* Request URL
* @ Param params
* Request parameters. The request parameters should be in the form of name1 = value1 & name2 = value2.
* @ Return URL indicates the response of the Remote resource.
*/
Public static String sendGet (String url, String params)
{
String result = "";
BufferedReader in = null;
Try
{
String urlName = url + "? "+ Params;
URL realUrl = new URL (urlName );
// Open the connection with the URL
URLConnection conn = realUrl. openConnection ();
// Set common request attributes
Conn. setRequestProperty ("accept ","*/*");
Conn. setRequestProperty ("connection", "Keep-Alive ");
Conn. setRequestProperty ("user-agent ",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1 )");
// Establish the actual connection
Conn. connect ();
// Obtain all response header fields
Map <String, List <String> map = conn. getHeaderFields ();
// Traverse all response header fields
For (String key: map. keySet ())
{
System. out. println (key + "--->" + map. get (key ));
}
// Define the BufferedReader input stream to read the URL response
In = new BufferedReader (
New InputStreamReader (conn. getInputStream ()));
String line;
While (line = in. readLine ())! = Null)
{
Result + = "\ n" + line;
}
}
Catch (Exception e)
{
System. out. println ("an exception occurred when sending a GET request! "+ E );
E. printStackTrace ();
}
// Use finally blocks to close the input stream
Finally
{
Try
{
If (in! = Null)
{
In. close ();
}
}
Catch (IOException ex)
{
Ex. printStackTrace ();
}
}
Return result;
}

/**
* Send a POST method request to a specified URL
*
* @ Param url
* Request URL
* @ Param params
* Request parameters. The request parameters should be in the form of name1 = value1 & name2 = value2.
* @ Return URL indicates the response of the Remote resource.
*/
Public static String sendPost (String url, String params)
{
PrintWriter out = null;
BufferedReader in = null;
String result = "";
Try
{
URL realUrl = new URL (url );
// Open the connection with the URL
URLConnection conn = realUrl. openConnection ();
// Set common request attributes

Conn. setRequestProperty ("accept ","*/*");
Conn. setRequestProperty ("connection", "Keep-Alive ");
Conn. setRequestProperty ("user-agent ",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1 )");
// You must set the following two rows to send a POST request:
Conn. setDoOutput (true );
Conn. setDoInput (true );
// Obtain the output stream corresponding to the URLConnection object
Out = new PrintWriter (conn. getOutputStream ());
// Send Request Parameters
Out. print (params );
// Flush the buffer of the output stream
Out. flush ();
// Define the BufferedReade r input stream to read the URL response
In = new BufferedReader (
New InputStreamReader (conn. getInputStream ()));
String line;
While (line = in. readLine ())! = Null)
{
Result + = "\ n" + line;
}
}
Catch (Exception e)
{
System. out. println ("an exception occurred when sending the POST request! "+ E );
E. printStackTrace ();
}
// Use finally blocks to close output streams and input streams
Finally
{
Try
{
If (out! = Null)
{
Out. close ();
}
If (in! = Null)
{
In. close ();
}
}
Catch (IOException ex)
{
Ex. printStackTrace ();
}
}
Return result;
}
} To send a get request, you only need to call the connect () method of URLConnection to establish the actual connection. To send a post request, you need to obtain the OutputStream of URLConnection, then output the request parameters to the network, such as the above program !!!

4. activity Code

Public class GetPostMain extends Activity
{
Button get, post;
EditText show;
@ Override
Public void onCreate (Bundle savedInstanceState)
{
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
Get = (Button) findViewById (R. id. get );
Post = (Button) findViewById (R. id. post );
Show = (EditText) findViewById (R. id. show );
Get. setOnClickListener (new OnClickListener ()
{
@ Override
Public void onClick (View v)
{
String response = GetPostUtil
. SendGet ("http: // 192.168.65.1: 8080/abc/a. jsp", null );
Show. setText (response );

}
});
Post. setOnClickListener (new OnClickListener ()
{
@ Override
Public void onClick (View v)
{
String response = GetPostUtil
. SendPost ("http: // 192.168.65.1: 8080/abc/login. jsp"
, "Name = crazyit.org & pass = leegang ");
Show. setText (response );

}
});
}
}

 

The get and post requests sent by this program are all sent to the local LAN: http: // 192/168. 65.1: 8080/abc application two pages are sent, this application is deployed on the local web application;
Url: http://greatverve.cnblogs.com/archive/2011/12/26/android-get-post.html

GET/POST requests for Android-Http connections

The Apache HttpClient (org. apache. http. *) module is provided in the Android SDK. This module involves two important classes: HttpGet and HttpPost. Creation steps: 1. Create an HttpGet (or HttpPost) object and pass the URL to be requested to an HttpGet (or HttpPost) object through the constructor; 2. Use the execute method of the DefaultHttpClient class to send an http get or http post request and return the HttpResponse object. 3. Use the getEntity method of the HttpResponse interface to return the response information. Although both are implemented in this way, there are some differences between the two. The specific code is as follows: http get request: String url; // step 1, create an HttpGet object HttpGet httpGet = new HttpGet (url); // step 2, use the execute method to send an http get request and return the HttpResponse object httpResponse = new defaulthttpclient(cmd.exe cute (httpGet ); if (httpResponse. getStatusLine (). getStatusCode () = 200) {// step 3, use the getEntity method to return the result String result = EntityUtils. toString (httpResponse. getEntity ();} http post request: String url; // Step 1: Create an HttpPost object HttpPost httpPost = new HttpPost (url ); // set the http post request parameters using the NameValuePair Object List <NameValuePair> params = new ArrayList <NameValuePair> (); params. add (new BasicNameValuePair ("bookname", etBookName. getText (). toString (); // sets the httpPost request parameter httpPost. setEntity (new UrlEncodedFormEntity (params, HTTP. UTF_8); // step 2, use the execute method to send an http get request and return the HttpResponse object httpResponse = new defaulthttpclient(cmd.exe cute (httpPost); if (httpResponse. getStatusLine (). getStatusCode () = 200) {// step 3, use the getEntity method to return the result String result = EntityUtils. toString (httpResponse. getEntity ();} The above is an explanation of the GET and POST methods. There are similarities and differences between the two.
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.