Android submits parameters to web applications through GET and POST

Source: Internet
Author: User

Android submits parameters to web applications through GET and POST
How to upload data to a web application
Application interface:
Video name: title
Duration: timelength
Save, click the Save button to submit to the web application, and develop Manageservlet in the web application to receive data.
Get Method
Server:
Public class ManageServlet extends HttpServlet
{
Private static final long serialVersionUID = 1L;
Protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOExceptionprotected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String title = request. getParameter ("title ");
Title = new String (title. getBytes ("ISO8859-1"), "UTF-8 ");
String timelength = request. getParameter ("timelength ");
System. out. println ("video name:" + title );
System. out. println ("Duration:" + timelength );
}
Protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{

}
}


Android end
Public class MainActivity extends Activity
{
Private EditText titleText;
Private EditText lengthText;
Public void onCreate (Bundle savedInstance)
{
Super. onCreate (Bundle savedInstance );
SetContentView (R. layout. main );
TitleText = (EditText) this. findViewById (R. id. title );
LengthText = (EditText) this. findViewById (R. id. timelength );
Button saveButton = (Button) this. findViewById (R. id. button );
SaveButton. setOnClickListener (new ButtonClickListener ());
}
Private static class ButtonClickListener implements View. OnClickListener
{
Public void onClick (View v)
{
String title = titleText. getText (). toString ();
String length = lengthText. getText (). toString ();
Boolean result = NewsService. save (title, length );
If (result)
{
Toast. makeText (getApplicationContext (), R. string. success, 1). show ();
} Else {
Toast. makeText (getApplicationContext (), R. string. error, 1). show ();
}
}
}
}


/* Save data */
The get post request parameter of the web application that submits data to the network through HTTP protocol. For data of less than 2 K, post must be used. To use the get method, you need to append the parameter to the path.




Public class NewsService
{
Public static boolean save (String title, String length)
{
String path = "http: // 192.168.1.100: 8080/web/ManageServlet ";
Map Params = new HashMap ();
Params. put ("title", title );
Params. put ("timelength", length );
Try
{
Return sendGETRequest (path, params, "UTF-8 ");
} Catch (Exception e)
{
E. printStackTrace ();
}
Return false;
}
/* Send a get request */
Private static boolean sendGETRequest (String path, Map Params, String ecoding) throws Exception
{
// Http: // 192.168.1.100: 8080/web/ManageServlet? Title = xxx & timelength = 90
StringBuilder url = new StringBuilder (path );
Url. append ("? ");
For (Map. Entry Entry: params. entrySet () // iteration sets each element.
{
Url. append (entry. getKey (). append ("= ");
Url. append (URLEncoder. encode (entry. getValue (), ecoding ));
Url. append ("&");
}
Url. deleteCharAt (url. length ()-1 );
HttpURLConnection conn = (HttpURLConnection) new URL (url. toString (). openConnection ();
Conn. setConnectTimeout (5000 );
Conn. setRequestMethod ("GET ");
If (conn. getResponseCode () = 200)
{
Return true;
}
Return false;
}
}
The reasons for Garbled text when submitting Chinese characters are as follows:
1. URL encoding is not performed on Chinese parameters when parameters are submitted.
Modify url. append (entry. getValue );
2, Tomcat server uses ISO8859-1 encoding by default to get the parameter value
Server added title = new String (title. getBytes ("ISO8859-1"), "UTF-8 ");


If there are many parameters, the conversion is troublesome. You can use a filter without transcoding.
Create filter: EncodingFilter
Filter all paths. You can modify the URL Pattern/Servlet Name /*
Public class EncodingFilter implements Filter
{
Public void destroy (){}
Public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException // this method is called upon each request
{
HttpServletRequest req = (HttpServletRequest) request;
If ("GET". equals (req. getMethod ()))
{
EncodingHttpServletRequest wrapper = new EncodingHttpServletRequest (req );
Chain. doFilter (wrapper, response );
} Else {
Req. setCharacterEncoding ("UTF-8 ");
Chain. doFilter (request, response );
}


}
Public void init (FilterConfig fConfig) thhrows ServletException {}

}
Create an EncodingHttpServletRequest class
Public class EncodingHttpServletRequest extends HttpServletRequestWrapper
{
Private HttpServletRequest request;
Public EncodingHttpServletRequest (HttpServletRequest request)
{
Super (request );
This. request = request;
}
// Check the Override getParameter method @ Override
Public String getParameter (String name)
{
String value = request. getParameter (name );
If (value! = Null)
{
Try {
Value = new String (value. getBytes ("ISO8859-1"), "UTF-8 ");
} Catch (UnsupportedEncodingException e)
{}
}
Return value;
}
}






POST method
Http
POST/web/ManageServlet HTTP/1.1 method/path/version
Data Types that Accept can receive
Referer http: // 192.168.1.100: 8080/web/index. jsp Source Path
Accept-Language
User-Agent vendor Browser
Content-Type: specifies the Content Type of the extracted data application/x-www-form-urlencoded
Accept-Encoding:
Host: 192.168.1.100; 8080
Content-Length: used to specify the total Length of data extraction 26
Connection: Keep-Alive




Title = liming & timelength = 90 extract data


Server:
Public class ManageServlet extends HttpServlet
{
Private static final long serialVersionUID = 1L;
Protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOExceptionprotected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String title = request. getParameter ("title ");
// Title = new String (title. getBytes ("ISO8859-1"), "UTF-8 ");
String timelength = request. getParameter ("timelength ");
System. out. println ("video name:" + title );
System. out. println ("Duration:" + timelength );
}
Protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{

}
}


Android end
Public class MainActivity extends Activity
{
Private EditText titleText;
Private EditText lengthText;
Public void onCreate (Bundle savedInstance)
{
Super. onCreate (Bundle savedInstance );
SetContentView (R. layout. main );
TitleText = (EditText) this. findViewById (R. id. title );
LengthText = (EditText) this. findViewById (R. id. timelength );
Button saveButton = (Button) this. findViewById (R. id. button );
SaveButton. setOnClickListener (new ButtonClickListener ());
}
Private static class ButtonClickListener implements View. OnClickListener
{
Public void onClick (View v)
{
String title = titleText. getText (). toString ();
String length = lengthText. getText (). toString ();
Boolean result = NewsService. save (title, length );
If (result)
{
Toast. makeText (getApplicationContext (), R. string. success, 1). show ();
} Else {
Toast. makeText (getApplicationContext (), R. string. error, 1). show ();
}
}
}
}


/* Save data */
The get post request parameter of the web application that submits data to the network through HTTP protocol. For data of less than 2 K, post must be used. To use the get method, you need to append the parameter to the path.




Public class NewsService
{
Public static boolean save (String title, String length)
{
String path = "http: // 192.168.1.100: 8080/web/ManageServlet ";
Map Params = new HashMap ();
Params. put ("title", title );
Params. put ("timelength", length );
Try
{
Return sendPOSTRequest (path, params, "UTF-8 ");
} Catch (Exception e)
{
E. printStackTrace ();
}
Return false;
}
/* Send a POST Request */
Private static boolean sendPOSTRequest (String path, Map Params, String ecoding) throws Exception
{
// Title = liming & timelength = 90
StringBuilder data = new StringBuilder ();
If (params! = Null &&! Params. isEmpty ())
{
For (Map. Entry Entry: params. entrySet () // iteration sets each element.
{
Data. append (entry. getKey (). append ("= ");
Data. append (URLEncoder. encode (entry. getValue (), ecoding ));
Data. append (entry. getKey (). append ("&");
}
Data. deleteCharAt (data. length ()-1 );
}
Byte [] entity = data. toString (). getBytes (); // byte data is obtained by UTF-8 by default
HttpURLConnection conn = (HttpURLConnection) new URL (path). openConnection ();
Conn. setConnectTimeout (5000 );
Conn. setRequestMethod ("POST ");
Conn. setDoOutput (true); // allow external data output
Conn. setRequestProperty ("Content-Type", "application/x-www-form-urlencoded ");
Conn. setRequestProperty ("Content-Length", String. valueOf (entity. length ));
OutputStream outStream = conn. getOutputStream ();
OutStream. write (entity); // The data is not written to the web application, but is output to the cache. The data is output to the web application only after the response code is obtained.
If (conn. getResponseCode () = 200)
{
Return true;
}

Return false;
}

Android HttpClient framework
Complete the functions completed by the browser
Public class NewsService
{
Public static boolean save (String title, String length)
{
String path = "http: // 192.168.1.100: 8080/web/ManageServlet ";
Map Params = new HashMap ();
Params. put ("title", title );
Params. put ("timelength", length );
Try
{
Return sendHttpClientPOSTRequest (path, params, "UTF-8 ");
} Catch (Exception e)
{
E. printStackTrace ();
}
Return false;
}
/* Send a POST Request */
Private static boolean sendHttpClientPOSTRequest (String path, Map Params, String ecoding) throws Exception
{
List Pairs = new ArrayList (); // Store Request Parameters
If (params! = Null &&! = Params. isEmpty ())
{
For (Map. Entry Entry: params. entrySet ())
{
Pairs. add (new BasicNameValuePair (entry. getKey (), entry. getValue ()));

}
}
// Title = liming & timelength = 90
UrlEncodingFormEntity entity = new UrlEncodingFormEntity (pairs, encoding );
HttpPost httpPost = new HttpPost (path );
HttpPost. setEntity (entity );
DefaultHttpClient client = new DefaultHttpClient ();
Client.exe cute (httpPost );
HttpResponse response = client.exe cute (httpPost );
If (response. getStatusLine (). getStatusCode () = 200)
{
Return true;
}
Return false;
}

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.