Tagged with: Android source code source upload
Volley does not explain, the Android official Web request library.
The source code addresses are:
[Email Protected]:com314159/volleymultipartrequest.git
is based on
Https://github.com/smanikandan14/Volley-demo
The great God has changed, but the great God's code has a bug, the upload file is unsuccessful.
Note: My demo inside also integrates the okhttp, does not need the classmate to ignore this kind can
Implementation method:
1. Add three jar packages,
Httpcore-4.3.2.jar
Httpclient-4.3.5.jar
Httpmime-4.3.5.jar
2. Implement Multipartstack
Package Com.example.volleytest;import Java.io.file;import Java.io.ioexception;import java.util.map;import Org.apache.http.httpentity;import Org.apache.http.httpresponse;import Org.apache.http.client.httpclient;import Org.apache.http.client.methods.httpdelete;import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; Import Org.apache.http.client.methods.httpget;import Org.apache.http.client.methods.httppatch;import Org.apache.http.client.methods.httppost;import Org.apache.http.client.methods.httpput;import Org.apache.http.client.methods.httpurirequest;import Org.apache.http.entity.bytearrayentity;import Org.apache.http.entity.contenttype;import Org.apache.http.entity.mime.httpmultipartmode;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.defaulthttpclient;import Org.apache.http.params.httpconnectionparams;import org.apache.http.Params. Httpparams;import Org.apache.http.protocol.http;import Com.android.volley.authfailureerror;import Com.android.volley.request;import Com.android.volley.request.method;import Com.android.volley.toolbox.HurlStack ;/** * @author Zhicheng Guo * @version October 7, 2014 11:00:52 This stack is used to upload files, and if there is no stack, the upload file is unsuccessful */public class MultiPart Stack extends Hurlstack {@SuppressWarnings ("unused") private static final String TAG = MultiPartStack.class.getSimpleName (); Private final static String Header_content_type = "Content-type"; @Overridepublic httpresponse performrequest (Request <?> request,map<string, string> additionalheaders) throws IOException, Authfailureerror {if (! ( Request instanceof Multipartrequest) {return super.performrequest (request, additionalheaders);} else {return performmultipartrequest (request, additionalheaders);}} private static void Addheaders (Httpurirequest httprequest, map<string, string> headers) {for (String key:h Eaders.keyset ()) { Httprequest.setheader (Key, Headers.get (key)); }}public HttpResponse performmultipartrequest (request<?> request,map<string, String> additionalHeaders) Throws IOException, Authfailureerror {httpurirequest HttpRequest = createmultipartrequest (Request, Additionalheade RS); Addheaders (HttpRequest, additionalheaders); Addheaders (HttpRequest, Request.getheaders ()); Httpparams httpparams = Httprequest.getparams (); int TIMEOUTMS = REQUEST.GETTIMEOUTMS (); Todo:reevaluate This connection timeout based on + wide-scale//data collection and possibly different for WiFi vs. 3G. Httpconnectionparams.setconnectiontimeout (Httpparams, 5000); Httpconnectionparams.setsotimeout (Httpparams, TIMEOUTMS); /* Make a thread safe Connection manager for the client */HttpClient HttpClient = new Defaulthttpclient (httpparams ); Return Httpclient.execute (HttpRequest);} Static HttpUrirequest createmultipartrequest (request<?> Request, map<string, string> additionalheaders) throws authfailureerror {switch (Request.getmethod ()) {case Method.deprecated_get_or_post: { This is the deprecated-on-the-needs to being handled for backwards compatibility. If the request ' s post body is null, then the assumption is, and the request is/GET. Otherwise, it is assumed and the request is a POST. byte[] Postbody = Request.getbody (); if (postbody! = null) {HttpPost postrequest = new HttpPost (Request.geturl ()); if (request.getbodycontenttype () = null) Postrequest.addheader (Header_content_type, Request.getbodycont Enttype ()); Httpentity entity; entity = new Bytearrayentity (postbody); Postrequest.setentity (entity); Return Postrequest; } else {return new HttpGet (Request.geturl ()); }} case Method.GET:return new HttpGet (Request.geturl ()); Case Method.DELETE:return New Httpdelete (Request.geturl ()); Case Method.post: {httppost postrequest = new HttpPost (Request.geturl ()); Postrequest.addheader (Header_content_type, Request.getbodycontenttype ()); Setmultipartbody (postrequest,request); return postrequest; } case method.put: {httpput putrequest = new Httpput (Request.geturl ()); if (request.getbodycontenttype () = null) Putrequest.addheader (Header_content_type, Request.getbodycontentty PE ()); Setmultipartbody (putrequest,request); return putrequest; }//Added in source code of volley Libray. Case Method.patch: {Httppatch patchrequest = new Httppatch (Request.geturl ()); if (request.getbodycontenttype () = null) Patchrequest.addheader (Header_content_type, Request.getbodycontenttype ()); return patchrequest; } Default:throw New IllegalStateException ("Unknown request method."); }}/** * If Request is multipartrequest type and then set multipartentity in the * HttpRequest object. * * @param HttpRequest * @param request * @throws authfailureerror */private static void Setmultipartbody (Httpentityenclo Singrequestbase httprequest,request<?> request) throws Authfailureerror {//Return if Request is not multipartreque Stif (! ( Request instanceof Multipartrequest) {return;} Multipartentity multipartentity = new//multipartentity (httpmultipartmode.browser_compatible); Multipartentitybuilder builder = multipartentitybuilder.create ();/* Example for setting a httpmultipartmode */ Builder.setmode (HttpmultipartmoDe. browser_compatible);//Iterate the fileuploadsmap<string, file> fileUpload = ((multipartrequest) request). Getfileuploads (); for (map.entry<string, file> entry:fileUpload.entrySet ()) {Builder.addpart ((String) Entry.getkey ()), New Filebody ((File) entry.getvalue ());} ContentType ContentType = Contenttype.create (HTTP. Plain_text_type, HTTP. UTF_8);//Iterate the stringuploadsmap<string, string> stringupload = ((multipartrequest) request). Getstringuploads (); for (map.entry<string, string> entry:stringUpload.entrySet ()) {try {Builder.addpart (( String) Entry.getkey ()), New Stringbody ((String) Entry.getvalue (), contentType)); catch (Exception e) {e.printstacktrace ();}} Httprequest.setentity (Builder.build ());}}
3. Implement Multipartrequest, this interface is for easy expansion
Package Com.example.volleytest;import java.io.file;import java.util.map;/** * @author Zhicheng Guo * @version October 7, 2014 Morning 11:04:36 */public interface multipartrequest {public void Addfileupload (String param,file File); public void Addstringupload (String param,string content); Public map<string,file> getfileuploads (); Public map<string,string> getstringuploads (); }
/** * Copyright Mani Selvaraj * * Licensed under the Apache License, Version 2.0 (the "License"); * You are not a use 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 appli Cable law or agreed into writing, software * Distributed under the License is distributed on a "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. */package Com.example.volleytest;import Java.io.file;import Java.io.unsupportedencodingexception;import Java.util.hashmap;import Java.util.map;import Com.android.volley.networkresponse;import Com.android.volley.request;import Com.android.volley.response;import Com.android.volley.Response.ErrorListener; Import Com.android.volley.response.listener;import com.android.volley.toolbox.httpheaderparser;/** * MultipartrequeSt-to handle the large file uploads. * Extended from Jsonrequest. You might want-to-stringrequest based on your response type. * @author Mani Selvaraj * */public class Multipartstringrequest extends request<string> implements Multipartrequest {Private final listener<string> mlistener;/* to hold the parameter name and the File to upload */private Map<stri ng,file> fileuploads = new hashmap<string,file> ();/* to hold the parameter name and the String content to upload */private map<string,string> stringuploads = new hashmap<string,string> (); /** * Creates a new request with the given method. * * @param method The request {@link method} to use * @param URL URL for fetch the string at * @param listener Listener to receive the String response * @param errorlistener Error Listener, or null to ignore errors */Publ IC multipartstringrequest (int method, String URL, listener<string> Listener, errorlistEner Errorlistener) {Super (method, URL, errorlistener); Mlistener = listener; } public void Addfileupload (String param,file File) {fileuploads.put (param,file); } public void Addstringupload (String param,string content) {stringuploads.put (param,content); }/** * file to be uploaded */public map<string,file> getfileuploads () {return fileuploads; }/** * Parameters to upload */public map<string,string> getstringuploads () {return stringuploads; } @Override protected response<string> parsenetworkresponse (Networkresponse Response) {String pars Ed try {parsed = new String (Response.data, Httpheaderparser.parsecharset (response.headers)); } catch (Unsupportedencodingexception e) {parsed = new String (response.data); } return Response.success (parsed, httpheaderparser.parsecacheheaders (Response)); } @Overrideprotected void Deliverresponse (StrinG response) {if (Mlistener! = null) {mlistener.onresponse (response);}} /** * NULL means do not upload */public String Getbodycontenttype () {return null; }}
3. How to use:
/**
* Upload files via put
* @param URL
* @param files
* @param params
* @param Responselistener
* @param Errorlistener
* @param Tag
*/
Public Static void addputuploadfilerequest (final StringURL,
Final map<string, file>files, final map<string, string> params,
Final Listener<string>Responselistener, final errorlistenerErrorlistener,
Final Objecttag) {
if (null = =URL | | null = = Responselistener) {
return;
}
Multipartstringrequest multipartrequest =new multipartstringrequest (
Request.method. PUT ,url, responselistener, errorlistener) {
@Override
Public Map<string, file> getfileuploads () {
return files;
}
@Override
Public Map<string, string> getstringuploads () {
return params;
}
};
LOG.I (TAG,"Volley put:uploadfile" + URL );
Mainapplication.getvolleyqueue (). Add (multipartrequest);
}
Android volley for file upload function