Android submits parameters to Web apps via get and post

Source: Internet
Author: User

How to upload data to Web applications
Application interface:
Video Name: Title
Duration: timelength
Save, click the Save button to submit to the Web app, develop Manageservlet in the Web app to receive data.
Get mode
Service side:
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 side
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 */
Data submitted through the HTTP protocol to the Web application on the network get post submission parameters, for 2K or less data can be, more than 2K must use post. Use the Get method to attach 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<string,string> params = new hashmap<string,string> ();
Params.put (("title", title);
Params.put ("timelength", length);
Try
{
Return Sendgetrequest (Path,params, "UTF-8");
} catch (Exception e)
{
E.printstacktrace ();
}
return false;
}
/* Send GET Request */
private static Boolean sendgetrequest (String path,map<string, string> 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<string,string> Entry:params.entrySet ())//iterate over each element of the collection
{
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;
}
}
Submission of Chinese words garbled, resulting in garbled reasons:
1, when the parameter is submitted, the Chinese parameter is not URL encoded
Modify Url.append (Entry.getvalue);
2,tomcat server By default is ISO8859-1 encoding to get the parameter value
The server adds title = new String (title.getbytes ("iso8859-1"), "UTF-8");


If a lot of parameters, the conversion is cumbersome, you can use the filter, do not have to transcode
New 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 every time the request arrives
{
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{}

}
New Class Encodinghttpservletrequest
public class Encodinghttpservletrequest extends Httpservletrequestwrapper
{
private HttpServletRequest request;
Public encodinghttpservletrequest (HttpServletRequest request)
{
Super (Request);
This.request=request;
}
Tick 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 mode
HTTP protocol Introduction
Post/web/manageservlet http/1.1 Mode/path/version
Accept data types that can be received
Referer http://192.168.1.100:8080/web/index.jsp Source Path
Accept-language
User-agent that vendor browser
Content-type: Used to specify the content type for extracting data application/x-www-form-urlencoded
Accept-encoding:
host:192.168.1.100;8080
Content-length: Used to specify the total length of the extracted data 26
Connection:keep-alive




TITLE=LIMING&AMP;TIMELENGTH=90 Extracting data


Service side:
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 side
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 */
Data submitted through the HTTP protocol to the Web application on the network get post submission parameters, for 2K or less data can be, more than 2K must use post. Use the Get method to attach 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<string,string> params = new hashmap<string,string> ();
Params.put (("title", title);
Params.put ("timelength", length);
Try
{
Return Sendpostrequest (Path,params, "UTF-8");
} catch (Exception e)
{
E.printstacktrace ();
}
return false;
}
/* Send POST Request */
private static Boolean sendpostrequest (String path,map<string, string> params,string ecoding) throws Exception
{
Title=liming&timelength=90
StringBuilder data=new StringBuilder ();
if (Params!=null &&!params.isempty ())
{
For (Map.entry<string,string>entry:params.entryset ())//iterate over each element of the collection
{
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 (); Using UTF-8 to get byte data by default
HttpURLConnection conn= (httpurlconnection) New URL (path). OpenConnection ();
Conn.setconnecttimeout (5000);
Conn.setrequestmethod ("POST");
Conn.setdooutput (TRUE); Allow external output data
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 app, it is output to the cache only and output to the Web app only after the response code is obtained
if (Conn.getresponsecode () ==200)
{
return true;
}

return false;
}

Android httpclient Frame
Ability to complete browser completion
public class Newsservice
{
public static Boolean Save (String title,string length)
{
String Path = "Http://192.168.1.100:8080/web/ManageServlet";
map<string,string> params = new hashmap<string,string> ();
Params.put (("title", title);
Params.put ("timelength", length);
Try
{
Return Sendhttpclientpostrequest (Path,params, "UTF-8");
} catch (Exception e)
{
E.printstacktrace ();
}
return false;
}
/* Send POST Request */
private static Boolean sendhttpclientpostrequest (String path,map<string, string> params,string ecoding) throws Exception
{
list<namevaluepair> pairs = new arraylist<namevaluepair> (); Store Request Parameters
if (params!=null &&!=params.isempty ())
{
For (map.entry<string,string> 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.execute (HttpPost);
HttpResponse response = Client.execute (HttpPost);
if (Response.getstatusline (). Getstatuscode () ==200)
{
return true;
}
return false;
}

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.