Go to Android network programming using httpclient bulk upload file Multipartentitybuilder

Source: Internet
Author: User
Tags http post

Please respect other people's labor results, reproduced please specify the Source: Android Network programming using HttpClient bulk upload files

Http://www.tuicool.com/articles/Y7reYb

I have described the use of httpcient in the article "Android Network programming using HTTP access to network resources", here is not the exhaustion, interested friends can go to see. Here is the main introduction of how to implement file upload via HttpClient.

1. Preliminary knowledge:

Uploading files before HttpCient4.3 the main use of the Multipartentity class, but now this class is not recommended to use. The class with which it is substituted is multipartentitybuilder.

Let's look at the Multipartentitybuilder class below:

Multipartentitybuilder This class is primarily used to create httpentity. Its main methods are:

Modifiers and types

Methods and descriptions

Multipartentitybuilder

Addbinarybody (String name, byte[] b)

Adds the data as a binary byte array.

Multipartentitybuilder

Addbinarybody (string name, byte[] B, ContentType ContentType, string filename)

Adds the data as a binary byte array.

Multipartentitybuilder

Addbinarybody (String name, file file)

Adds the data as a binary form of the file.

Multipartentitybuilder

Addbinarybody (string name, file file, ContentType ContentType, string filename)

Adds the data as a binary form of the file.

Multipartentitybuilder

Addbinarybody (String name, inputstream Stream)

Multipartentitybuilder

Addbinarybody (string name, inputstream stream, ContentType ContentType, string filename)

Adds data to the input stream as a binary form.

Multipartentitybuilder

Addpart (String name, contentbody contentbody)

Add data of type contentbody .

Multipartentitybuilder

Addtextbody (string name, string text)

Add text data.

Multipartentitybuilder

Addtextbody (string name, string text, ContentType ContentType)

Adds text data to the specified content type.

Httpentity

Build ()

Create a httpentity.

Static Multipartentitybuilder

Create ()

Creates a Multipartentitybuilder object.

Multipartentitybuilder

setboundary (String boundary)

Set the bounds.

Multipartentitybuilder

Setcharset (Charset Charset)

Sets the encoding format of the request.

Multipartentitybuilder

Setlaxmode ()

Multipartentitybuilder

SetMode (httpmultipartmode mode)

Set the mode.

Multipartentitybuilder

Setstrictmode ()

Main Method Description:

Addbinarybody , Addpart , The addtextbody method is used to add data to be uploaded, and the method used to add data from the table above can be found in the key-value type. So on the server side we can get the data of the corresponding key through the Request.getpart ("KeyName") method. You can also obtain the client through the Request.getparts () method to submit all data through the three methods above.

1. You can add data of File, InputStream, byte[] type directly through the addbinarybody method.

2. Only contentbody types of data can be added through the Addpart method, and String is already provided in the Org.apache.http.entity.mime.content package ,File , and InputStream corresponding to the contentbody type subclass, such as Filebody, Inputstreambody, Stringbody, With these classes we can convert data of type String, file, and InputStream to contentbody type.

3. We can easily add text data using the addtextbody method.

2. Uploading files via Httpcient

The Android side needs to add Httpcore-4.3.2.jar, Httpmime-4.3.5.jar two packs. Two packages are indispensable.

Here I use the latest version of the httpcient, we can from http://hc.apache.org/ downloads.cgi Download the required jar package, if the above Web site can not open, we do not worry, I have the project needs to upload the jar package csdn "Httpcomponents-client-4.3.5-bin.zip" Need friends can go to download.

Android Terminal Project Core code:
HttpClient client=new defaulthttpclient ();//Open a client http request HttpPost post = new HttpPost (URL);//Create an HTTP POST request  Multi Partentitybuilder builder = multipartentitybuilder.create ();//builder.setcharset (Charset.forname ("uft-8"));// Set the encoding format of the request Builder.setmode (httpmultipartmode.browser_compatible);//Set browser compatibility mode int count=0;for (File file:files) {// Filebody filebody = new Filebody (file);//convert files to stream object Filebody//builder.addpart ("file" +count, filebody); Builder.addbinarybody ("File" +count, file); count++;} Builder.addtextbody ("Method", Params.get ("method"));//Set request parameter Builder.addtextbody ("FileTypes", Params.get (" FileTypes "));//Set request parameter httpentity entity = Builder.build ();//Generate HTTP POST entity  post.setentity (entity);// Set the request parameter HttpResponse response = Client.execute (post);//initiate the request and return the requested response if (Response.getstatusline (). Getstatuscode () ==200 ) {return true;} return false;

Code Analysis:

The above code mainly implemented a multi-file upload, in order to facilitate the server side save the file, the above code set the name called FileTypes parameters, FileTypes is uploaded by the file type name stitching into a string, such as ". Jpg.png.docx";

The server side can get the type of file to save by getting the parameter named FileTypes and splitting it into a character array.

Server-side project core code:

Server segments mainly use the SERVLET3.0 API, the main methods are:

1. Request.getparameter ("");//Gets the string type of data that the client adds through the Addtextbody method.

2. Request.getpart ("");//Get client through addbinarybody,addpart,addtextbody Method adds the specified data, returning the object of part type.

3. Request.getparts ();//Get clients through addbinarybody,addpart,addtextbody The collection<part> method adds all the data that returns an object of type.

4. Part.getname ();//Gets the name of the uploaded file that is the key specified when uploading.

5. Part.getsize ()//Gets the size unit of the uploaded file in bytes.

String filetypes=request.getparameter ("filetypes");//Gets all file types uploaded by the client string[]typearray=filetypes.substring (1). Split ("\ \"); /Split the file type string into a string array try {iterator<part>iterator=request.getparts (). Iterator (); int Count=0;while ( Iterator.hasnext ()) {//traverse all files uploaded by the client if (count>=typearray.length) break;//jump out of loop if the size of the file type array is exceeded Iterator.next ();//system.out.println ("Part.getsize ()" +part.getsize ());//Gets the size of the uploaded file//system.out.println (" Part.getname () "+part.getname ()");//Get the name of the uploaded file and the key name when adding data file=new file ("e:\\upload\\" +count+ ".") +typearray[count++]); InputStream Inputstream=part.getinputstream (); FileOutputStream fos=new fileoutputstream (file); Byte[]buffer=new byte[1024];int Len=0;while ((Len=inputStream.read ( Buffer)!=-1) {fos.write (buffer,0, Len);} Inputstream.close (); Fos.close ();}} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}

Code Analysis:

The server side is implemented by the servlet by calling the Request.getparameter ("FileTypes") method to get all the file types uploaded by the client, and then splitting the file type string into a string array. The client is removed through the Request.getparts () method via addbinarybody,addpart,addtextbody Upload all the data and then traverse the data collection to save the file.

Due to the prior and client contracts, the order in which the files are added before the request parameter is added, it is possible to determine the number of client uploads based on the length of the split file type array, so the program jumps out of the loop and does not save the file when the above code traversal is beyond the length of the type array. Because the following part is a parameter, not the file to be saved.

Program run:

3. Complete the Project code: Mainactivity.java
Package Com.jph.ufh.activity;import Java.io.file;import Java.util.arraylist;import java.util.hashmap;import Java.util.map;import Com.jph.ufh.r;import Com.jph.ufh.service.uploadservice;import Android.app.Activity;import Android.os.bundle;import Android.os.environment;import Android.os.handler;import Android.os.Message;import Android.view.view;import android.widget.toast;/** * Bulk upload files via httpclient * @author JPH * date:2014.10.09 */public class Ma Inactivity extends Activity {private arraylist<file>files;private map<string, string>params; Handler mhandler=new Handler () {@Overridepublic void Handlemessage (Message msg) {//TODO auto-generated method Stubswitch (msg.what) {case UploadService.UPLOAD_SUCCESS:Toast.makeText (mainactivity.this, "Upload succeeded", Toast.length_long). Show (); break;} Super.handlemessage (msg);}}; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); files=new arraylist<file> ();p Arams=neW hashmap<string, String> ();} public void upload (View v) {files.clear ();p arams.clear (); File File=new file (Environment.getexternalstoragedirectory (), "kaola.jpg"); File File2=new file (Environment.getexternalstoragedirectory (), "Test.docx"); File File3=new file (Environment.getexternalstoragedirectory (), "test.jpg"); Files.add (file); Files.add (file2); Files.add (FILE3); StringBuffer sbfiletypes=new StringBuffer (); for (File tempfile:files) {String filename=tempfile.getname (); Sbfiletypes.append (Getfiletype (FileName));} Params.put ("FileTypes", Sbfiletypes.tostring ());p Arams.put ("Method", "upload"); Uploadservice uploadservice=new Uploadservice (Mhandler); Uploadservice.uploadfiletoserver (params, files);} /** * Gets the type of file * @param filename: file name * @return file type */private string Getfiletype (String fileName) {//TODO auto-generated Method Stubreturn filename.substring (Filename.lastindexof ("."), Filename.length ());}}
Uploadservice.java
Package Com.jph.ufh.service;import Java.io.file;import Java.io.ioexception;import java.util.arraylist;import Java.util.map;import Org.apache.http.httpentity;import Org.apache.http.httpresponse;import Org.apache.http.client.clientprotocolexception;import Org.apache.http.client.httpclient;import Org.apache.http.client.methods.httppost;import Org.apache.http.entity.mime.httpmultipartmode;import Org.apache.http.entity.mime.multipartentitybuilder;import Org.apache.http.impl.client.defaulthttpclient;import Android.os.Handler; /** * Upload files with httpclient, support multi-file upload * @author jph * date:2014.10.09 */public class Uploadservice {private static String url= "HT Tp://10.219.57.16:8080/serverforupload/servletforupload ";//private static String url=" http://10.110.6.58:8080/ Serverforupload/servletforupload ";p ublic static final int upload_success=0x123;public static final int upload_fail= 0x124;private Handler handler;public uploadservice (Handler Handler) {//TODO auto-generated constructor Stubthis.handler=handleR;} /** * @param params request parameters, including the requested method parameters such as: "Upload", * request the uploaded file type filetypes such as: ". Jpg.png.docx" * @param files to upload file collection */publ IC void Uploadfiletoserver (final map<string, string> params, final arraylist<file>files) {//TODO Auto-generated method Stubnew Thread (new Runnable () {@Overridepublic void Run () {//TODO auto-generated method Stubtry {i F (Uploadfiles (Url,params,files)) {handler.sendemptymessage (upload_success);//notify the main thread that the data was sent successfully}else {//Send data to server failed}} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}). Start ();} /** * @param url servlet address * @param params parameter to pass * @param files to upload file * @return True if upload success else false * @th Rows clientprotocolexception * @throws ioexception */private boolean uploadfiles (String url,map<string, string> Params,arraylist<file>files) throws Clientprotocolexception, IOException {HttpClient client=new Defaulthttpclient ();//Open a client http request HttpPost post = new HttpPost (URL);//Create an HTTP POST request MultiparteNtitybuilder builder = multipartentitybuilder.create ();//builder.setcharset (Charset.forname ("uft-8"));// Set the encoding format of the request Builder.setmode (httpmultipartmode.browser_compatible);//Set browser compatibility mode int count=0;for (File file:files) {// Filebody filebody = new Filebody (file);//convert files to stream object Filebody//builder.addpart ("file" +count, filebody); Builder.addbinarybody ("File" +count, file); count++;} Builder.addtextbody ("Method", Params.get ("method"));//Set request parameter Builder.addtextbody ("FileTypes", Params.get (" FileTypes "));//Set request parameter httpentity entity = Builder.build ();//Generate HTTP POST entity post.setentity (entity);// Set the request parameter HttpResponse response = Client.execute (post);//initiate the request and return the requested response if (Response.getstatusline (). Getstatuscode () ==200 ) {return true;} return false;}}

Go to Android network programming using HttpClient bulk upload files Multipartentitybuilder

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.