recently in the Android file upload, requires the form form to submit, the project uses the Afinal framework has the file upload function, but always can not be written with PHP server docking, unable to upload success. Read source discovery: Afinal used a great god to write the Multipartentity.java generated form form content, but the resulting content format is not standard, and there are many problems, such as: first read all the files into memory, and then generate a byte stream written to Socket So here's the question: what if it's a hundreds of MB file?
A few searches, inspired by this article (which I have reproduced, but the sample code has expired), I found the Apache source Httpcomponents-client-4.3.6-src.zip, in an example found an important component Multipartentitybuilder, you can generate form form forms of httpentity, with httpentity, no matter what HTTP framework you are, you should be able to use.
Don't know how to use it? Like this:
HttpPost HttpPost =Newhttppost (URL);. httppost.setentity (Makemultipartentity (params, files)); HttpResponse Response=gethttpclient (). Execute (httppost); ..Private StaticHttpClient mclient;Private StaticHttpClient gethttpclient () {if(Mclient = =NULL) { //if (Build.VERSION.SDK_INT >= 9); //will not walk this class of case, based on HttpURLConnection if(Build.VERSION.SDK_INT >=8) {mclient=androidhttpclient.newinstance (Getuseragent ()); }Else{mclient=Newdefaulthttpclient (); } } returnmclient;}
Multipartentitybuilder usage is organized as follows:
Need to use Httpmime-4.3.6.jar and Httpcore-4.3.3.jar in Httpcomponents-client-4.3.6-bin.zip.
Public StaticHttpentity makemultipartentity (list<namevaluepair>params, Final map<string, file>files) {Multipartentitybuilder Builder=multipartentitybuilder.create (); Builder.setmode (httpmultipartmode.strict); //if there are sockettimeoutexception and so on, you can modify this enumeration//Builder.setcharset (Charset.forname ("UTF-8")); //do not use this will cause the server to receive no parameters if(params!=NULL&¶ms. Size () >0) { for(Namevaluepair P:params) {builder.addtextbody (P.getname (), P.getvalue (), ContentType.TEXT_PLAIN.withCharset ("UTF-8")); } } if(Files! =NULL&& files.size () >0) {Set<entry<string, file>> entries =Files.entryset (); for(Entry<string, file>entry:entries) {Builder.addpart (Entry.getkey (),NewFilebody (Entry.getvalue ())); } } returnbuilder.build ();}
An example of Apache is also attached, which can be found in Httpcomponents-client-4.3.6-bin.zip.
/** ==================================================================== * Licensed to the Apache software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * Distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * under the Apache License, Version 2.0 (The * "License"); You are not a use of this file except in compliance * with the License. Obtain a copy of the License at * *http://www.apache.org/licenses/LICENSE-2.0* * unless required by applicable or agreed to writing, * software distributed under the License is distribute D on an * ' as is ' BASIS, without warranties or CONDITIONS of any * KIND, either express or implied. See the License for the * Specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary Contributions made by many * individuals on behalf of the Apache software Foundation. For more * information on the Apache software Foundation, please see * <http://www.apache.org/*. **/Package Org.apache.http.examples.entity.mime;import Java.io.file;import org.apache.http.httpentity;import Org.apache.http.client.methods.closeablehttpresponse;import Org.apache.http.client.methods.httppost;import Org.apache.http.entity.contenttype;import Org.apache.http.entity.mime.multipartentitybuilder;import Org.apache.http.entity.mime.content.filebody;import Org.apache.http.entity.mime.content.stringbody;import Org.apache.http.impl.client.closeablehttpclient;import Org.apache.http.impl.client.httpclients;import Org.apache.http.util.EntityUtils;/** * Example How to use Multipart/form encoded POST request.*/ Public classClientmultipartformpost { Public Static voidMain (string[] args) throws Exception {if(Args.length! =1) {System. out. println ("File Path not given"); System.exit (1); } closeablehttpclient httpclient=Httpclients.createdefault (); Try{httppost HttpPost=NewHttpPost ("http://localhost:8080"+"/servlets-examples/servlet/requestinfoexample"); Filebody bin=NewFilebody (NewFile (args[0])); Stringbody Comment=NewStringbody ("A binary file of some kind", Contenttype.text_plain); Httpentity reqentity=multipartentitybuilder.create (). Addpart ("bin", Bin). Addpart ("Comment", comment). build (); Httppost.setentity (reqentity); System. out. println ("Executing request"+httppost.getrequestline ()); Closeablehttpresponse Response=Httpclient.execute (HttpPost); Try{System. out. println ("----------------------------------------"); System. out. println (Response.getstatusline ()); Httpentity resentity=response.getentity (); if(Resentity! =NULL) {System. out. println ("Response Content Length:"+resentity.getcontentlength ()); } entityutils.consume (resentity); } finally{response.close (); } } finally{httpclient.close (); } }}
Android uses Multipartentitybuilder to implement file uploads like form form submission