public class MultipartRequest
- Object
- ConnectionRequest
- MultipartRequest
ImplementsIOProgressListener
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();
}
}
}
Constructors
public MultipartRequest() | Initialize variables |
Methods
public static boolean isLeaveInputStreamsOpen() | Special flag to keep input stream files open after they are read |
public static void setLeaveInputStreamsOpen(boolean aLeaveInputStreamsOpen) | Special flag to keep input stream files open after they are read |
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. |
public String getBoundary() | Returns the boundary string which is normally generated based on system time |
public void setBoundary(String boundary) | Sets the boundary string, normally you don’t need this method. |
protected void initConnection(Object connection) | Invoked to initialize HTTP headers, cookies etc. |
public void addData(String name, byte[] data, String mimeType) | Adds a binary argument to the arguments |
public void addData(String name, String filePath, String mimeType)
throws IOException | Adds a binary argument to the arguments |
public void addData(String name, InputStream data, long dataSize, String mimeType) | Adds a binary argument to the arguments, notice the input stream will be read only during submission |
public void setFilename(String arg, String filename) | Sets the filename for the given argument |
public void addArgumentNoEncoding(String key, String value) | Add an argument to the request response without encoding it, this is useful for arguments which are already encoded |
public void addArgumentNoEncoding(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 value |
public void addArgumentNoEncodingArray(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 value |
public void addArgument(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 key |
public void addArgument(String name, String value) | Add an argument to the request response |
protected long calculateContentLength() | |
protected void buildRequestBody(OutputStream os)
throws IOException | Invoked when send body is true, by default sends the request arguments based on “POST” conventions |
public int getContentLength() | Returns the content length header value |
public boolean onRedirect(String url) | This is a callback method that been called when there is a redirect. |
public boolean isManualRedirect() | By default redirect responses (302 etc.) are handled manually in multipart requests |
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. |
public boolean isBase64Binaries() | Set to true to encode binary data as base 64 |
public void setBase64Binaries(boolean base64Binaries) | Set to true to encode binary data as base 64 |
public boolean equals(Object o) | Indicates whether some other object is “equal to” this one. |
public int hashCode() | Returns a hash code value for the object. |
Inherited nested types
Inherited fields
Inherited methods
From ConnectionRequest
getDefaultCacheMode, setDefaultCacheMode, isReadResponseForErrorsDefault, setReadResponseForErrorsDefault, isHandleErrorCodesInGlobalErrorHandler, setHandleErrorCodesInGlobalErrorHandler, getCookieHeader, setCookieHeader, isCookiesEnabledDefault, setCookiesEnabledDefault, isDefaultFollowRedirects, setDefaultFollowRedirects, isReadTimeoutSupported, purgeCacheDirectory, getDefaultUserAgent, setDefaultUserAgent, setUseNativeCookieStore, isNativeCookieSharingSupported, fetchJSON, fetchJSONAsync, getCacheMode, setCacheMode, isCheckSSLCertificates, setCheckSSLCertificates, isInsecure, setInsecure, getResponseData, getHttpMethod, setHttpMethod, addRequestHeader, removeRequestHeader, removeRequestHeaderIfUnchanged, checkSSLCertificates, getReadTimeout, setReadTimeout, getCachedData, purgeCache, cacheUnmodified, cookieReceived, cookieSent, initCookieHeader, getResponseCode, getResposeCode, shouldConvertPostToGetOnRedirect, readHeaders, readErrorCodeHeaders, getHeader, getHeaders, getHeaderFieldNames, getYield, shouldAutoCloseResponse, handleIOException, handleRuntimeException, handleException, canGetSSLCertificates, getSSLCertificates, handleErrorResponseCode, retry, readResponse, postResponse, createRequestURL, shouldWriteUTFAsGetBytes, kill, shouldStop, isPausable, pause, resume, isPost, setPost, addArgument, removeArgument, removeAllArguments, addArgumentArray, addArguments, getContentType, setContentType, isWriteRequest, setWriteRequest, isReadRequest, setReadRequest, isPaused, setPaused, isKilled, setKilled, getPriority, setPriority, getUserAgent, setUserAgent, isFollowRedirects, setFollowRedirects, getTimeout, setTimeout, ioStreamUpdate, getUrl, setUrl, addResponseListener, removeResponseListener, addResponseCodeListener, addExceptionListener, removeResponseCodeListener, removeExceptionListener, hasResponseListeners, fireResponseListener, isDuplicateSupported, setDuplicateSupported, validate, getDisposeOnCompletion, setDisposeOnCompletion, getShowOnInit, setShowOnInit, getSilentRetryCount, setSilentRetryCount, isFailSilently, setFailSilently, isReadResponseForErrors, setReadResponseForErrors, getResponseContentType, isRedirecting, getDestinationFile, setDestinationFile, getDestinationStorage, setDestinationStorage, isCookiesEnabled, setCookiesEnabled, setChunkedStreamingMode, downloadImageToStorage, downloadImageToStorage, downloadImageToStorage, downloadImageToStorage, downloadImageToStorage, downloadImageToStorage, downloadImageToFileSystem, downloadImageToFileSystem, downloadImageToFileSystem, downloadImageToFileSystem, downloadImageToFileSystem, downloadImageToFileSystem, getRequestBody, setRequestBody, setRequestBody, getRequestBodyData, getResponseErrorMessage
Constructor details
MultipartRequest
public MultipartRequest()Method details
isLeaveInputStreamsOpen
public static boolean isLeaveInputStreamsOpen()Returns
setLeaveInputStreamsOpen
public static void setLeaveInputStreamsOpen(boolean aLeaveInputStreamsOpen)Parameters
aLeaveInputStreamsOpenboolean- the leaveInputStreamsOpen to set
setCanFlushStream
public static void setCanFlushStream(boolean flush)getBoundary
public String getBoundary()Returns
setBoundary
public void setBoundary(String boundary)Parameters
boundaryString- the boundary string
initConnection
protected void initConnection(Object connection)Parameters
connectionObject- the connection object
addData
public void addData(String name, byte[] data, String mimeType)Parameters
nameString- the name of the data
databyte[]- the data as bytes
mimeTypeString- the mime type for the content
addData
public void addData(String name, String filePath, String mimeType)
throws IOExceptionParameters
nameString- the name of the file data
filePathString- the path of the file to upload
mimeTypeString- the mime type for the content
Throws
IOException- if the file cannot be opened
addData
public void addData(String name, InputStream data, long dataSize, String mimeType)Parameters
nameString- the name of the data
dataInputStream- the data stream
dataSizelong- 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
mimeTypeString- the mime type for the content
setFilename
public void setFilename(String arg, String filename)Parameters
argString- the argument name
filenameString- the file name
addArgumentNoEncoding
public void addArgumentNoEncoding(String key, String value)Parameters
keyString- the key of the argument
valueString- the value for the argument
addArgumentNoEncoding
public void addArgumentNoEncoding(String key, String[] value)Parameters
keyString- the key of the argument
valueString[]- the value for the argument
addArgumentNoEncodingArray
public void addArgumentNoEncodingArray(String key, String... value)Parameters
keyString- the key of the argument
valueString...- the value for the argument
addArgument
public void addArgument(String name, String[] value)Parameters
nameString- the key of the argument
valueString[]- the value for the argument
addArgument
public void addArgument(String name, String value)Parameters
nameString- the key of the argument
valueString- the value for the argument
calculateContentLength
protected long calculateContentLength()buildRequestBody
protected void buildRequestBody(OutputStream os)
throws IOExceptionParameters
osOutputStream- output stream of the body
Throws
getContentLength
public int getContentLength()Returns
onRedirect
public boolean onRedirect(String url)Parameters
urlString- the url to be redirected
Returns
isManualRedirect
public boolean isManualRedirect()Returns
setManualRedirect
public void setManualRedirect(boolean autoRedirect)Parameters
autoRedirectboolean- the autoRedirect to set
isBase64Binaries
public boolean isBase64Binaries()Returns
setBase64Binaries
public void setBase64Binaries(boolean base64Binaries)Parameters
base64Binariesboolean- the base64Binaries to set
equals
public boolean equals(Object o)hashCode
public int hashCode()