Android Instance code to send HTTP requests (including file uploads, servlet receives) _android

Source: Internet
Author: User
Tags http request response code

Copy Code code as follows:

/**
* Submit data to server via HTTP protocol, implement form submission function, including uploading files
* @param actionurl upload Path
* @param params request parameter key is parameter name, value
* @param file Upload files
*/
public static void Postmultiparams (String actionurl, map<string, string> params, formbean[] files) {
try {
Postmethod post = new Postmethod (ActionURL);
list<art> formparams = new arraylist<art> ();
For (map.entry<string, string> entry:params.entrySet ()) {
Formparams.add (New Stringpart (Entry.getkey (), Entry.getvalue ()));
}

if (files!=null)
for (Formbean file:files) {
FileName is the file name that you want to save when you receive it on the server, filepath is the local file path (including the source file name), and Filebean contains these two attributes
Formparams.add (New Filepart ("File", File.getfilename (), New file (File.getfilepath ()));
}

part[] Parts = new part[formparams.size ()];
iterator<art> pit = Formparams.iterator ();
int i=0;

while (Pit.hasnext ()) {
parts[i++] = Pit.next ();
}
If there are garbled can try the way
Stringpart sp = new Stringpart ("TEXT", "TestValue", "GB2312");
Filepart fp = new Filepart ("File", "Test.txt", New File ("./temp/test.txt"), NULL, "GB2312"
Postmethod.getparams (). Setcontentcharset ("GB2312");

Multipartrequestentity MRP = new Multipartrequestentity (parts, Post.getparams ());
Post.setrequestentity (MRP);

Execute POST method
HttpClient client = new HttpClient ();
int code = Client.executemethod (POST);
SYSTEM.OUT.PRINTLN (code);
Catch ...
}

The above code can successfully simulate the Java client to send a POST request, the server can also receive and save the file
Main method of Java side test:

Copy Code code as follows:

public static void Main (string[] args) {
String ActionURL = "Http://192.168.0.123:8080/WSserver/androidUploadServlet";
map<string, string> strparams = new hashmap<string, string> ();
Strparams.put ("Paramone", "Valueone");
Strparams.put ("Paramtwo", "valuetwo");
formbean[] files = new formbean[]{new Formbean ("Dest1.xml", "F:/testpostsrc/main.xml")};
Httptool.postmultiparams (Actionurl,strparams,files);
}


I thought it was done, and the result is a transplant to Android, the compiler is fine.
But the runtime throws an exception first to say that the Postmethod class cannot be found, Org.apache.commons.httpclient.methods.PostMethod This class is absolutely contained;
Another anomaly is verifyerror. There are several times in the development of this anomaly are helpless, that is not compatible with the SDK or how, who knows to tell me to say ~ ~
So look at the Internet has a direct analysis of the content of HTTP request build POST request, also have to find with upload file, take down to run some problems, then directly by running the above Java project sent the POST request, in the servlet print out the request content, Then to follow the stitching string and stream finally to achieve! The code is as follows:
***********************************************************

Copy Code code as follows:

/**
* Constructs the request content through the splicing way, realizes the parameter transmission and the file transmission
* @param actionurl
* @param params
* @param files
* @return
* @throws IOException
*/
public static string post (string ActionURL, map<string, string> params,
Map<string, file> files) throws IOException {

String boundary = Java.util.UUID.randomUUID (). toString ();
String PREFIX = "--", Linend = "\ r \ n";
String multipart_from_data = "Multipart/form-data";
String CHARSET = "UTF-8";

URL uri = new URL (actionurl);
HttpURLConnection conn = (httpurlconnection) uri.openconnection ();
Conn.setreadtimeout (5 * 1000); The maximum length of time to cache
Conn.setdoinput (TRUE);//Allow input
Conn.setdooutput (TRUE);//Allow output
Conn.setusecaches (FALSE); Caching is not allowed
Conn.setrequestmethod ("POST");
Conn.setrequestproperty ("Connection", "keep-alive");
Conn.setrequestproperty ("Charsert", "UTF-8");
Conn.setrequestproperty ("Content-type", Multipart_from_data + "; boundary=" + boundary);

//First set of parameters for the group text type
StringBuilder sb = new StringBuilder ();
for (map.entry<string, string> entry:params.entrySet ()) {
Sb.append (PREFIX);
Sb.append (boundary);
Sb.append (linend);
Sb.append ("Content-disposition:form-data; Name=\ "" + entry.getkey () + "\" + linend);
Sb.append ("Content-type:text/plain; charset= "+ charset+linend);
Sb.append ("content-transfer-encoding:8bit" + linend);
Sb.append (linend);
Sb.append (Entry.getvalue ());
Sb.append (linend);
}

DataOutputStream OutStream = new DataOutputStream (Conn.getoutputstream ());
Outstream.write (Sb.tostring (). GetBytes ());
Send file Data
if (files!=null)
For (map.entry<string, file> file:files.entrySet ()) {
StringBuilder sb1 = new StringBuilder ();
Sb1.append (PREFIX);
Sb1.append (boundary);
Sb1.append (Linend);
Sb1.append ("Content-disposition:form-data; Name=\ "File\"; Filename=\ "" +file.getkey () + "\" "+linend);
Sb1.append ("Content-type:application/octet-stream; Charset= "+charset+linend);
Sb1.append (Linend);
Outstream.write (Sb1.tostring (). GetBytes ());

InputStream is = new FileInputStream (File.getvalue ());
byte[] buffer = new byte[1024];
int len = 0;
while (len = is.read (buffer))!=-1) {
Outstream.write (buffer, 0, Len);
}

Is.close ();
Outstream.write (Linend.getbytes ());
}

End of Request flag
Byte[] End_data = (PREFIX + boundary + PREFIX + linend). GetBytes ();
Outstream.write (End_data);
Outstream.flush ();
Get Response code
int res = Conn.getresponsecode ();
if (res = = 200) {
InputStream in = Conn.getinputstream ();
int ch;
StringBuilder SB2 = new StringBuilder ();
while (ch = in.read ())!=-1) {
Sb2.append ((char) ch);
}
}
Outstream.close ();
Conn.disconnect ();
return in.tostring ();
}

**********************
The code in the button response:
**********************

Copy Code code as follows:

public void OnClick (View v) {
String ActionURL = Getapplicationcontext (). getString (R.string.wtsb_req_upload);
map<string, string> params = new hashmap<string, string> ();
Params.put ("strParamName", "Strparamvalue");
Map<string, file> files = new hashmap<string, file> ();
Files.put ("TempAndroid.txt", New File ("/sdcard/temp.txt"));
try {
Httptool.postmultiparams (ActionURL, params, files);
Catch ...

***************************
Server-side servlet code:
***************************

Copy Code code as follows:

public void DoPost (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {

Print Request.getinputstream to check request content
Httptool.printstreamcontent (Request.getinputstream ());

RequestContext req = new Servletrequestcontext (request);
if (Fileupload.ismultipartcontent (req)) {
Diskfileitemfactory factory = new Diskfileitemfactory ();
Servletfileupload fileupload = new Servletfileupload (factory);
Fileupload.setfilesizemax (file_max_size);

List items = new ArrayList ();
try {
Items = fileupload.parserequest (request);
Catch ...

Iterator it = Items.iterator ();
while (It.hasnext ()) {
Fileitem Fileitem = (fileitem) it.next ();
if (Fileitem.isformfield ()) {
System.out.println (fileitem.getfieldname () + "" +fileitem.getname () + "" +new String ( Fileitem.getstring (). GetBytes ("Iso-8859-1"), "GBK");
} else {
System.out.println (fileitem.getfieldname () + "" +fileitem.getname () + "" +
Fileitem.isinmemory () + "" +fileitem.getcontenttype () + "" +fileitem.getsize ());
if (fileitem.getname ()!=null && fileitem.getsize ()!=0) {
File FullFile = new file (Fileitem.getname ());
File NewFile = new file (File_save_path+fullfile.getname ());
try {
Fileitem.write (newFile);
} catch ...
} else {
System.out.println ("No file choosen or empty file");
}
}
}
}
}

public void Init () throws Servletexception {
Read the Init-param configured in the Web.xml
File_max_size = Long.parselong (This.getinitparameter ("file_max_size"));//upload file size limit
File_save_path = This.getinitparameter ("File_save_path");//File Save location
}

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.