Class MultipartRequest
- All Implemented Interfaces:
IOProgressListener
A multipart post request allows a developer to submit large binary data files to the server in a multipart mime post request. This is a standard method for large binary file uploads to webservers and data services.
The sample code below includes both the client code using the upload capabilities as well as a simple sample servlet that can accept multipart data:
// File: MultipartClientSample.java
MultipartRequest request = new MultipartRequest();
request.setUrl(url);
request.addData("myFileName", fullPathToFile, "text/plain")
NetworkManager.getInstance().addToQueue(request);
// File: UploadServlet.java
@WebServlet(name = "UploadServlet", urlPatterns = {"/upload"})
@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 100, // 10 MB
maxFileSize = 1024 * 1024 * 150, // 50 MB
maxRequestSize = 1024 * 1024 * 200) // 100 MB
public class UploadServlet extends HttpServlet {
@Override
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
Collection parts = req.getParts();
Part data = parts.iterator().next();
try(InputStream is = data.getInputStream()) {}
// store or do something with the input stream
}
}
}
The sample code below demonstrates uploading to the filestack.com API.
public void pictureUpload(final Callback resultURL) {
String picture = Capture.capturePhoto(1024, -1);
if(picture!=null){
String filestack = "https://www.filestackapi.com/api/store/S3?key=MY_KEY&filename=myPicture.jpg";
MultipartRequest request = new MultipartRequest() {
protected void readResponse(InputStream input) throws IOException {
JSONParser jp = new JSONParser();
Map result = jp.parseJSON(new InputStreamReader(input, "UTF-8"));
String url = (String)result.get("url");
if(url == null) {
resultURL.onError(null, null, 1, result.toString());
return;
}
resultURL.onSucess(url);
}
};
request.setUrl(filestack);
try {
request.addData("fileUpload", picture, "image/jpeg");
request.setFilename("fileUpload", "myPicture.jpg");
NetworkManager.getInstance().addToQueue(request);
} catch(IOException err) {
err.printStackTrace();
}
}
}
-
Nested Class Summary
Nested classes/interfaces inherited from class ConnectionRequest
ConnectionRequest.CachingMode, ConnectionRequest.SSLCertificate -
Field Summary
Fields inherited from class ConnectionRequest
PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_LOW, PRIORITY_NORMAL, PRIORITY_REDUNDANT -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoidaddArgument(String name, String value) Add an argument to the request responsevoidaddArgument(String name, String[] value) Add an argument to the request response as an array of elements, this will trigger multiple request entries with the same keyvoidaddArgumentNoEncoding(String key, String value) Add an argument to the request response without encoding it, this is useful for arguments which are already encodedvoidaddArgumentNoEncoding(String key, String[] value) Add an argument to the request response as an array of elements, this will trigger multiple request entries with the same key, notice that this doesn't implicitly encode the valuevoidaddArgumentNoEncodingArray(String key, String... value) Add an argument to the request response as an array of elements, this will trigger multiple request entries with the same key, notice that this doesn't implicitly encode the valuevoidAdds a binary argument to the argumentsvoidaddData(String name, InputStream data, long dataSize, String mimeType) Adds a binary argument to the arguments, notice the input stream will be read only during submissionvoidAdds a binary argument to the argumentsprotected voidInvoked when send body is true, by default sends the request arguments based on "POST" conventionsprotected longbooleanReturns the boundary string which is normally generated based on system timeintReturns the content length header valueinthashCode()protected voidinitConnection(Object connection) Invoked to initialize HTTP headers, cookies etc.booleanSet to true to encode binary data as base 64static booleanSpecial flag to keep input stream files open after they are readbooleanBy default redirect responses (302 etc.) are handled manually in multipart requestsbooleanonRedirect(String url) This is a callback method that been called when there is a redirect.voidsetBase64Binaries(boolean base64Binaries) Set to true to encode binary data as base 64voidsetBoundary(String boundary) Sets the boundary string, normally you don't need this method.static voidsetCanFlushStream(boolean flush) Sending large files requires flushing the writer once in a while to prevent Out Of Memory Errors, Some J2ME implementation are not able to flush the streams causing the upload to fail.voidsetFilename(String arg, String filename) Sets the filename for the given argumentstatic voidsetLeaveInputStreamsOpen(boolean aLeaveInputStreamsOpen) Special flag to keep input stream files open after they are readvoidsetManualRedirect(boolean autoRedirect) By default redirect responses (302 etc.) are handled manually in multipart requests, set this to false to handle the redirect.Methods inherited from class ConnectionRequest
addArgument, addArgumentArray, addArguments, addExceptionListener, addRequestHeader, addResponseCodeListener, addResponseListener, cacheUnmodified, canGetSSLCertificates, checkSSLCertificates, cookieReceived, cookieSent, createRequestURL, downloadImageToFileSystem, downloadImageToFileSystem, downloadImageToFileSystem, downloadImageToFileSystem, downloadImageToFileSystem, downloadImageToFileSystem, downloadImageToStorage, downloadImageToStorage, downloadImageToStorage, downloadImageToStorage, downloadImageToStorage, downloadImageToStorage, fetchJSON, fetchJSONAsync, fireResponseListener, getCachedData, getCacheMode, getContentType, getCookieHeader, getDefaultCacheMode, getDefaultUserAgent, getDestinationFile, getDestinationStorage, getDisposeOnCompletion, getHeader, getHeaderFieldNames, getHeaders, getHttpMethod, getPriority, getReadTimeout, getRequestBody, getRequestBodyData, getResponseCode, getResponseContentType, getResponseData, getResponseErrorMessage, getResposeCode, getShowOnInit, getSilentRetryCount, getSSLCertificates, getTimeout, getUrl, getUserAgent, getYield, handleErrorResponseCode, handleException, handleIOException, handleRuntimeException, hasResponseListeners, initCookieHeader, ioStreamUpdate, isCheckSSLCertificates, isCookiesEnabled, isCookiesEnabledDefault, isDefaultFollowRedirects, isDuplicateSupported, isFailSilently, isFollowRedirects, isHandleErrorCodesInGlobalErrorHandler, isInsecure, isKilled, isNativeCookieSharingSupported, isPausable, isPaused, isPost, isReadRequest, isReadResponseForErrors, isReadResponseForErrorsDefault, isReadTimeoutSupported, isRedirecting, isWriteRequest, kill, pause, postResponse, purgeCache, purgeCacheDirectory, readErrorCodeHeaders, readHeaders, readResponse, removeAllArguments, removeArgument, removeExceptionListener, removeResponseCodeListener, removeResponseListener, resume, retry, setCacheMode, setCheckSSLCertificates, setChunkedStreamingMode, setContentType, setCookieHeader, setCookiesEnabled, setCookiesEnabledDefault, setDefaultCacheMode, setDefaultFollowRedirects, setDefaultUserAgent, setDestinationFile, setDestinationStorage, setDisposeOnCompletion, setDuplicateSupported, setFailSilently, setFollowRedirects, setHandleErrorCodesInGlobalErrorHandler, setHttpMethod, setInsecure, setKilled, setPaused, setPost, setPriority, setReadRequest, setReadResponseForErrors, setReadResponseForErrorsDefault, setReadTimeout, setRequestBody, setRequestBody, setShowOnInit, setSilentRetryCount, setTimeout, setUrl, setUseNativeCookieStore, setUserAgent, setWriteRequest, shouldAutoCloseResponse, shouldConvertPostToGetOnRedirect, shouldStop, shouldWriteUTFAsGetBytes, validate
-
Constructor Details
-
MultipartRequest
public MultipartRequest()Initialize variables
-
-
Method Details
-
isLeaveInputStreamsOpen
public static boolean isLeaveInputStreamsOpen()Special flag to keep input stream files open after they are read
Returns
the leaveInputStreamsOpen
-
setLeaveInputStreamsOpen
public static void setLeaveInputStreamsOpen(boolean aLeaveInputStreamsOpen) Special flag to keep input stream files open after they are read
Parameters
aLeaveInputStreamsOpen: the leaveInputStreamsOpen to set
-
setCanFlushStream
public static void setCanFlushStream(boolean flush) Sending large files requires flushing the writer once in a while to prevent Out Of Memory Errors, Some J2ME implementation are not able to flush the streams causing the upload to fail. This method can indicate to the upload to not use the flushing mechanism. -
getBoundary
Returns the boundary string which is normally generated based on system time
Returns
the multipart boundary string
-
setBoundary
Sets the boundary string, normally you don't need this method. Its useful to workaround server issues only. Notice that this method must be invoked before adding any elements.
Parameters
boundary: the boundary string
-
initConnection
Description copied from class:ConnectionRequestInvoked to initialize HTTP headers, cookies etc.
Parameters
connection: the connection object
- Overrides:
initConnectionin classConnectionRequest
-
addData
-
addData
Adds a binary argument to the arguments
Parameters
-
name: the name of the file data -
filePath: the path of the file to upload -
mimeType: the mime type for the content
Throws
IOException: if the file cannot be opened
- Throws:
IOException
-
-
addData
Adds a binary argument to the arguments, notice the input stream will be read only during submission
Parameters
-
name: the name of the data -
data: the data stream -
dataSize: @param dataSize the byte size of the data stream, if the data stream is a file the file size can be obtained using the FileSystemStorage.getInstance().getLength(file) method -
mimeType: the mime type for the content
-
-
setFilename
-
addArgumentNoEncoding
Add an argument to the request response without encoding it, this is useful for arguments which are already encoded
Parameters
-
key: the key of the argument -
value: the value for the argument
- Overrides:
addArgumentNoEncodingin classConnectionRequest
-
-
addArgumentNoEncoding
Add an argument to the request response as an array of elements, this will trigger multiple request entries with the same key, notice that this doesn't implicitly encode the value
Parameters
-
key: the key of the argument -
value: the value for the argument
- Overrides:
addArgumentNoEncodingin classConnectionRequest
-
-
addArgumentNoEncodingArray
Add an argument to the request response as an array of elements, this will trigger multiple request entries with the same key, notice that this doesn't implicitly encode the value
Parameters
-
key: the key of the argument -
value: the value for the argument
- Overrides:
addArgumentNoEncodingArrayin classConnectionRequest
-
-
addArgument
Add an argument to the request response as an array of elements, this will trigger multiple request entries with the same key
Parameters
-
key: the key of the argument -
value: the value for the argument
- Overrides:
addArgumentin classConnectionRequest
-
-
addArgument
Add an argument to the request response
Parameters
-
key: the key of the argument -
value: the value for the argument
- Overrides:
addArgumentin classConnectionRequest
-
-
calculateContentLength
protected long calculateContentLength() -
buildRequestBody
Invoked when send body is true, by default sends the request arguments based on "POST" conventions
Parameters
os: output stream of the body
- Overrides:
buildRequestBodyin classConnectionRequest- Throws:
IOException
-
getContentLength
public int getContentLength()Description copied from class:ConnectionRequestReturns the content length header value
Returns
the content length
- Overrides:
getContentLengthin classConnectionRequest
-
onRedirect
Description copied from class:ConnectionRequestThis is a callback method that been called when there is a redirect. IMPORTANT this feature doesn't work on all platforms and currently doesn't work on iOS which always implicitly redirects
Parameters
url: the url to be redirected
Returns
true if the implementation would like to handle this by itself
- Overrides:
onRedirectin classConnectionRequest
-
isManualRedirect
public boolean isManualRedirect()By default redirect responses (302 etc.) are handled manually in multipart requests
Returns
the autoRedirect
-
setManualRedirect
public void setManualRedirect(boolean autoRedirect) By default redirect responses (302 etc.) are handled manually in multipart requests, set this to false to handle the redirect. Notice that a redirect converts a post to a get.
Parameters
autoRedirect: the autoRedirect to set
-
isBase64Binaries
public boolean isBase64Binaries()Set to true to encode binary data as base 64
Returns
the base64Binaries
-
setBase64Binaries
public void setBase64Binaries(boolean base64Binaries) Set to true to encode binary data as base 64
Parameters
base64Binaries: the base64Binaries to set
-
equals
Description copied from class:ConnectionRequest- Overrides:
equalsin classConnectionRequest
-
hashCode
public int hashCode()- Overrides:
hashCodein classConnectionRequest
-