Android simulates HTTP multipart/form-data Request protocol information to upload images

Source: Internet
Author: User

Problem:

In Android applications, when entering user information, posting comments, and other operations are required, you will inevitably encounter the "form operation" (similar to web form operations) Upload image function.

In this case, HTTPConnection/ApacheHTTP of Android cannot be implemented through POST and GET methods.

Solution:


The Android client uploads images by simulating the HTTP multipart/form-data Request protocol.

/**
* File name: UploadImage. java
*
* Copyright: Apache License, Version 2.0
*
* Function Description: uploads image files.
*
* Creation date: 2011-5-10
*
* Author: Bert Lee
*/

/*
* Modification history:
*/
Public class UploadImage {
String multipart_form_data = "multipart/form-data ";
String twoHyphens = "--";
String boundary = "***************** fD4fH3gL0hK7aI6"; // Data Separator
String lineEnd = System. getProperty ("line. separator"); // The value is "\ r \ n" in Windows.

/*
* Upload the image content. For the format, see HTTP format.
* Renren Photos. upload in the "program calls" http://wiki.dev.renren.com/wiki/Photos.upload#.E7.A8.8B.E5.BA.8F.E8.B0.83.E7.94.A8
* The format is clearly explained.
* The format is as follows:
* -- ***************** FD4fH3hK7aI6
* Content-Disposition: form-data; name = "upload_file"; filename = "apple.jpg"
* Content-Type: image/jpeg
*
* Here is the file content, in the form of a binary stream
*/
Private void addImageContent (Image [] files, DataOutputStream output ){
For (Image file: files ){
StringBuilder split = new StringBuilder ();
Split. append (twoHyphens + boundary + lineEnd );
Split. append ("Content-Disposition: form-data; name = \" "+ file. getFormName () + "\"; filename = \ "" + file. getFileName () + "\" "+ lineEnd );
Split. append ("Content-Type:" + file. getContentType () + lineEnd );
Split. append (lineEnd );
Try {
// Send image data
Output. writeBytes (split. toString ());
Output. write (file. getData (), 0, file. getData (). length );
Output. writeBytes (lineEnd );
} Catch (IOException e ){
Throw new RuntimeException (e );
}
}
}

/*
* Construct the form field content. For the format, see HTTP protocol format (FireBug can capture relevant data ). (To upload the parameter values corresponding to the form)
* The format is as follows:
* -- ***************** FD4fH3hK7aI6
* Content-Disposition: form-data; name = "action"
* // An empty row is required.
* Upload
*/
Private void addFormField (Set <Map. Entry <Object, Object> params, DataOutputStream output ){
StringBuilder sb = new StringBuilder ();
For (Map. Entry <Object, Object> param: params ){
Sb. append (twoHyphens + boundary + lineEnd );
Sb. append ("Content-Disposition: form-data; name = \" "+ param. getKey () +" \ "" + lineEnd );
Sb. append (lineEnd );
Sb. append (param. getValue () + lineEnd );
}
Try {
Output. writeBytes (sb. toString (); // send form field data
} Catch (IOException e ){
Throw new RuntimeException (e );
}
}

/**
* Submit data directly to the server over HTTP to implement the form submission function.
* @ Param actionUrl: Upload path: www.2cto.com
* @ Param params the request parameter key is the parameter name and value is the parameter value.
* @ Param files Upload File Information
* @ Return returns the request result
*/
Public String post (String actionUrl, Set <Map. Entry <Object, Object> params, Image [] files ){
HttpURLConnection conn = null;
DataOutputStream output = null;
BufferedReader input = null;
Try {
URL url = new URL (actionUrl );
Conn = (HttpURLConnection) url. openConnection ();
Conn. setConnectTimeout (120000 );
Conn. setDoInput (true); // allow input
Conn. setDoOutput (true); // allow output
Conn. setUseCaches (false); // No Cache is used.
Conn. setRequestMethod ("POST ");
Conn. setRequestProperty ("Connection", "keep-alive ");
Conn. setRequestProperty ("Content-Type", multipart_form_data + "; boundary =" + boundary );

Conn. connect ();
Output = new DataOutputStream (conn. getOutputStream ());

AddImageContent (files, output); // Add Image Content

AddFormField (params, output); // Add form field content

Output. writeBytes (twoHyphens + boundary + twoHyphens + lineEnd); // data end mark
Output. flush ();

Int code = conn. getResponseCode ();
If (code! = 200 ){
Throw new RuntimeException ("request'" + actionUrl + "'failed! ");
}

Input = new BufferedReader (new InputStreamReader (conn. getInputStream ()));
StringBuilder response = new StringBuilder ();
String oneLine;
While (oneLine = input. readLine ())! = Null ){
Response. append (oneLine + lineEnd );
}

Return response. toString ();
} Catch (IOException e ){
Throw new RuntimeException (e );
} Finally {
// Uniformly release resources
Try {
If (output! = Null ){
Output. close ();
}
If (input! = Null ){
Input. close ();
}
} Catch (IOException e ){
Throw new RuntimeException (e );
}

If (conn! = Null ){
Conn. disconnect ();
}
}
}

Public static void main (String [] args ){
Try {
String response = "";

BufferedReader in = new BufferedReader (new FileReader ("config/actionUrl. properties "));
String actionUrl = in. readLine ();

// Read the name and value of the field corresponding to the form.
Properties formDataParams = new Properties ();
FormDataParams. load (new FileInputStream (new File ("config/formDataParams. properties ")));
Set <Map. Entry <Object, Object> params = formDataParams. entrySet ();

// Read the form field name and image path corresponding to the image.
Properties imageParams = new Properties ();
ImageParams. load (new FileInputStream (new File ("config/imageParams. properties ")));
Set <Map. Entry <Object, Object> images = imageParams. entrySet ();
Image [] files = new Image [images. size ()];
Int I = 0;
For (Map. Entry <Object, Object> image: images ){
Image file = new Image (image. getValue (). toString (), image. getKey (). toString ());
Files [I ++] = file;
}
// Image file = new Image ("images/apple.jpg", "upload_file ");
// Image [] files = new Image [0];
// Files [0] = file;

Response = new UploadImage (). post (actionUrl, params, files );
System. out. println ("returned result:" + response );
} Catch (IOException e ){
E. printStackTrace ();
}
}
}
 

From Yeju dongli
 

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.