Instance code for sending Http requests (including file upload and servlet reception) in Android

Source: Internet
Author: User

Copy codeThe Code is as follows :/**
* Submit data to the server over http to implement the form submission function, including uploading files
* @ Param actionUrl: Upload path
* @ Param params the request parameter key is the parameter name and value is the parameter value.
* @ Param file: upload a file
*/
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 name of the file to be saved when the server receives the file. filepath is the local file path (including the source file name), and filebean contains the 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 garbled characters appear, try again.
// 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.exe cuteMethod (post );
System. out. println (code );
} Catch...
}

The above code can successfully simulate a java client to send a post request, and the server can also receive and save files
The main method for java testing:

Copy codeThe Code is 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. As a result, it was no problem to compile the program after it was transplanted to the android project.
However, if an exception is thrown during the runtime, The PostMethod class cannot be found. The org. apache. commons. httpclient. methods. PostMethod class is definitely included;
Another exception is VerifyError. I am helpless when I encounter this exception several times during development. I think the SDK is incompatible or not. Can anyone tell me ~~
As a result, I have directly analyzed the content of the http request on the Internet to build a post request, and I have also found that the content with the uploaded file is always a problem, you can directly run the post request sent by the java project above, print the request content in the servlet, and finally implement it against the concatenated string and stream! The Code is as follows:
**************************************** *******************

Copy codeThe Code is as follows :/**
* Construct the request content through splicing to transmit parameters and files
* @ 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); // Maximum Cache Time
Conn. setDoInput (true); // allow input
Conn. setDoOutput (true); // allow output
Conn. setUseCaches (false); // cache 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 );

// Set parameters of the text type first
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 ());
}

// Request end mark
Byte [] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND). getBytes ();
OutStream. write (end_data );
OutStream. flush ();
// Get the 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 ();
}

**********************
Code in the button response:
**********************

Copy codeThe Code is 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 servlet code:
***************************

Copy codeThe Code is 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 web. xml
FILE_MAX_SIZE = Long. parseLong (this. getInitParameter ("file_max_size"); // specifies the size of the uploaded file.
FILE_SAVE_PATH = this. getInitParameter ("file_save_path"); // file storage 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.