public class ConnectionRequest
- Object
- ConnectionRequest
ImplementsIOProgressListener
Known subtypesAdsService, MultipartRequest, GZConnectionRequest, CachedDataService, ImageDownloadService, RSSService, TwitterRESTService
This class represents a connection object in the form of a request response
typically common for HTTP/HTTPS connections. A connection request is added to
the com.codename1.io.NetworkManager for processing in a queue on one of the
network threads. You can read more about networking in Codename One here
The sample code below fetches a page of data from the nestoria housing listing API.
You can see instructions on how to display the data in the com.codename1.components.InfiniteScrollAdapter
class. You can read more about networking in Codename One here.
int pageNumber = 1;
java.util.List<Map<String, Object>> fetchPropertyData(String text) {
try {
ConnectionRequest r = new ConnectionRequest();
r.setPost(false);
r.setUrl("http://api.nestoria.co.uk/api");
r.addArgument("pretty", "0");
r.addArgument("action", "search_listings");
r.addArgument("encoding", "json");
r.addArgument("listing_type", "buy");
r.addArgument("page", "" + pageNumber);
pageNumber++;
r.addArgument("country", "uk");
r.addArgument("place_name", text);
NetworkManager.getInstance().addToQueueAndWait(r);
Map result = new JSONParser().parseJSON(new InputStreamReader(new ByteArrayInputStream(r.getResponseData()), "UTF-8"));
Map response = (Map)result.get("response");
return (java.util.List<Map<String, Object>>)response.get("listings");
} catch(Exception err) {
Log.e(err);
return null;
}
}
Nested types
enum ConnectionRequest.CachingMode | There are 5 caching modes: |
class ConnectionRequest.SSLCertificate | Encapsulates an SSL certificate fingerprint. |
Fields
public static final byte PRIORITY_CRITICAL = 100 | A critical priority request will “push” through the queue to the highest point regardless of anything else and ignoring anything that is not in itself of critical priority. |
public static final byte PRIORITY_HIGH = 80 | A high priority request is the second highest level, it will act exactly like a critical priority with one difference. |
public static final byte PRIORITY_NORMAL = 50 | Normal priority executes as usual on the queue |
public static final byte PRIORITY_LOW = 30 | Low priority requests are mostly background tasks that should still be accomplished though |
public static final byte PRIORITY_REDUNDANT = 0 | Redundant elements can be discarded from the queue when paused |
Constructors
public ConnectionRequest() | Default constructor |
public ConnectionRequest(String url) | Construct a connection request to a url |
public ConnectionRequest(String url, boolean post) | Construct a connection request to a url |
Methods
public static ConnectionRequest.CachingMode getDefaultCacheMode() | The default value for the cacheMode property see #getCacheMode() |
public static void setDefaultCacheMode(ConnectionRequest.CachingMode aDefaultCacheMode) | The default value for the cacheMode property see #getCacheMode() |
public static boolean isReadResponseForErrorsDefault() | Determines the default value for #isReadResponseForErrors() |
public static void setReadResponseForErrorsDefault(boolean aReadResponseForErrorsDefault) | Determines the default value for #setReadResponseForErrors(boolean) |
public static boolean isHandleErrorCodesInGlobalErrorHandler() | When set to true (the default), the global error handler in NetworkManager should receive errors for response code as well |
public static void setHandleErrorCodesInGlobalErrorHandler(boolean aHandleErrorCodesInGlobalErrorHandler) | When set to true (the default), the global error handler in NetworkManager should receive errors for response code as well |
public static String getCookieHeader() | Workaround for https://bugs.php.net/bug.php?id=65633 allowing developers to customize the name of the cookie header to Cookie |
public static void setCookieHeader(String aCookieHeader) | Workaround for https://bugs.php.net/bug.php?id=65633 allowing developers to customize the name of the cookie header to Cookie |
public static boolean isCookiesEnabledDefault() | |
public static void setCookiesEnabledDefault(boolean aCookiesEnabledDefault) | |
public static boolean isDefaultFollowRedirects() | Enables/Disables automatic redirects globally and returns the 302 error code, IMPORTANT this feature doesn’t work on all platforms and currently doesn’t work on iOS which always implicitly redirects |
public static void setDefaultFollowRedirects(boolean aDefaultFollowRedirects) | Enables/Disables automatic redirects globally and returns the 302 error code, IMPORTANT this feature doesn’t work on all platforms and currently doesn’t work on iOS which always implicitly redirects |
public static boolean isReadTimeoutSupported() | Checks if this platform supports read timeouts. |
public static void purgeCacheDirectory()
throws IOException | Purges all locally cached files |
public static String getDefaultUserAgent() | |
public static void setDefaultUserAgent(String aDefaultUserAgent) | |
public static void setUseNativeCookieStore(boolean b) | Indicates whether the native Cookie stores should be used |
public static boolean isNativeCookieSharingSupported() | Checks if the platform supports sharing cookies between the native components (e.g. BrowserComponent) and ConnectionRequests. |
public static Map<String, Object> fetchJSON(String url)
throws IOException | Utility method that returns a JSON structure or throws an IOException in case of a failure. |
public static AsyncResource<Map<String, Object>> fetchJSONAsync(String url) | Fetches JSON asynchronously. |
public ConnectionRequest.CachingMode getCacheMode() | There are 5 caching modes: |
public void setCacheMode(ConnectionRequest.CachingMode cacheMode) | There are 5 caching modes: |
public boolean isCheckSSLCertificates() | |
public void setCheckSSLCertificates(boolean checkSSLCertificates) | |
public boolean isInsecure() | Checks if the request is insecure (default false). |
public void setInsecure(boolean insecure) | Turns off checking to make sure that SSL certificate is valid. |
public byte[] getResponseData() | This method will return a valid value for only some of the responses and only after the response was processed |
public String getHttpMethod() | Returns the http method |
public void setHttpMethod(String httpMethod) | Sets the http method for the request |
public void addRequestHeader(String key, String value) | Adds the given header to the request that will be sent |
public void removeRequestHeader(String key) | Removes a header previously added with addRequestHeader(String, String). |
public void removeRequestHeaderIfUnchanged(String key, String value) | Removes a header previously added with addRequestHeader(String, String), but only while it still holds value. |
protected void checkSSLCertificates(ConnectionRequest.SSLCertificate[] certificates) | A callback that can be overridden by subclasses to check the SSL certificates for the server, and kill the connection if they don’t pass muster. |
public int getReadTimeout() | Gets the read timeout for this connection. |
public void setReadTimeout(int timeout) | Sets the read timeout for the connection. |
protected void initConnection(Object connection) | Invoked to initialize HTTP headers, cookies etc. |
protected InputStream getCachedData()
throws IOException | This method should be overriden in CacheMode.MANUAL to provide offline caching. |
public void purgeCache() | Deletes the cache file if it exists, notice that this will not work for download files |
protected void cacheUnmodified()
throws IOException | This callback is invoked on a 304 server response indicating the data in the server matches the result we currently have in the cache. |
protected void cookieReceived(Cookie c) | Callback invoked for every cookie received from the server |
protected void cookieSent(Cookie c) | Callback invoked for every cookie being sent to the server |
protected String initCookieHeader(String cookie) | Allows subclasses to inject cookies into the request |
public int getResponseCode() | Returns the response code for this request, this is only relevant after the request completed and might contain a temporary (e.g. redirect) code while the request is in progress |
public int getResposeCode() | Deprecated Returns the response code for this request, this is only relevant after the request completed and might contain a temporary (e.g. redirect) code while the request is in progress |
protected boolean shouldConvertPostToGetOnRedirect() | This mimics the behavior of browsers that convert post operations to get operations when redirecting a request. |
protected void readHeaders(Object connection)
throws IOException | Allows reading the headers from the connection by calling the getHeader() method. |
protected void readErrorCodeHeaders(Object connection)
throws IOException | Allows reading the headers from the connection by calling the getHeader() method when a response that isn’t 200 OK is sent. |
protected String getHeader(Object connection, String header)
throws IOException | Returns the HTTP header field for the given connection, this method is only guaranteed to work when invoked from the readHeaders method. |
protected String[] getHeaders(Object connection, String header)
throws IOException | Returns the HTTP header field for the given connection, this method is only guaranteed to work when invoked from the readHeaders method. |
protected String[] getHeaderFieldNames(Object connection)
throws IOException | Returns the HTTP header field names for the given connection, this method is only guaranteed to work when invoked from the readHeaders method. |
protected int getYield() | Returns the amount of time to yield for other processes, this is an implicit method that automatically generates values for lower priority connections |
protected boolean shouldAutoCloseResponse() | Indicates whether the response stream should be closed automatically by the framework (defaults to true), this might cause an issue if the stream needs to be passed to a separate thread for reading. |
protected void handleIOException(IOException err) | Handles IOException thrown when performing a network operation |
protected void handleRuntimeException(RuntimeException err) | Handles an exception thrown when performing a network operation |
protected void handleException(Exception err) | Handles an exception thrown when performing a network operation, the default implementation shows a retry dialog. |
public boolean canGetSSLCertificates() | Checks to see if the platform supports getting SSL certificates. |
public ConnectionRequest.SSLCertificate[] getSSLCertificates()
throws IOException | Gets the server’s SSL certificates for this requests. |
protected void handleErrorResponseCode(int code, String message) | Handles a server response code that is not 200 and not a redirect (unless redirect handling is disabled) |
public void retry() | Retry the current operation in case of an exception |
public boolean onRedirect(String url) | This is a callback method that been called when there is a redirect. |
protected void readResponse(InputStream input)
throws IOException | Callback for the server response with the input stream from the server. |
protected void postResponse() | A callback method that’s invoked on the EDT after the readResponse() method has finished, this is the place where developers should change their Codename One user interface to avoid race conditions that might be triggered by modifications within readResponse. |
protected String createRequestURL() | Creates the request URL mostly for a get request |
protected void buildRequestBody(OutputStream os)
throws IOException | Invoked when send body is true, by default sends the request arguments based on “POST” conventions |
protected boolean shouldWriteUTFAsGetBytes() | Returns whether when writing a post body the platform expects something in the form of string.getBytes(“UTF-8”) or new OutputStreamWriter(os, “UTF-8”). |
public void kill() | Kills this request if possible |
protected boolean shouldStop() | Returns true if the request is paused or killed, developers should call this method periodically to test whether they should quit the current IO operation immediately |
protected boolean isPausable() | Return true from this method if this connection can be paused and resumed later on. |
public boolean pause() | Invoked to pause this opeation, this method will only be invoked if isPausable() returns true (its false by default). |
public boolean resume() | Called when a previously paused operation now has the networking time to resume. |
public boolean isPost() | Returns true for a post operation and false for a get operation |
public void setPost(boolean post) | Set to true for a post operation and false for a get operation, this will implicitly set the method to post/get respectively (which you can change back by setting the method). |
public void addArgument(String key, byte[] value) | Deprecated Add an argument to the request response |
public void removeArgument(String key) | Removes the given argument from the request |
public void removeAllArguments() | Removes all arguments |
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 key, String value) | Add an argument to the request response |
public void addArgumentArray(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 |
public void addArgument(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 |
public void addArguments(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 |
public String getContentType() | |
public void setContentType(String contentType) | |
public boolean isWriteRequest() | |
public void setWriteRequest(boolean writeRequest) | |
public boolean isReadRequest() | |
public void setReadRequest(boolean readRequest) | |
protected boolean isPaused() | |
protected void setPaused(boolean paused) | |
protected boolean isKilled() | |
protected void setKilled(boolean killed) | |
public byte getPriority() | The priority of this connection based on the constants in this class |
public void setPriority(byte priority) | The priority of this connection based on the constants in this class |
public String getUserAgent() | |
public void setUserAgent(String userAgent) | |
public boolean isFollowRedirects() | Enables/Disables automatic redirects globally and returns the 302 error code, IMPORTANT this feature doesn’t work on all platforms and currently doesn’t work on iOS which always implicitly redirects |
public void setFollowRedirects(boolean followRedirects) | Enables/Disables automatic redirects globally and returns the 302 error code, IMPORTANT this feature doesn’t work on all platforms and currently doesn’t work on iOS which always implicitly redirects |
public int getTimeout() | Indicates the timeout for this connection request |
public void setTimeout(int timeout) | Indicates the timeout for this connection request |
public int getContentLength() | Returns the content length header value |
public void ioStreamUpdate(Object source, int bytes) | Indicates the number of bytes that were read/written to/from the source stream |
public String getUrl() | |
public void setUrl(String url) | |
public void addResponseListener(ActionListener<NetworkEvent> a) | Adds a listener that would be notified on the CodenameOne thread of a response from the server. |
public void removeResponseListener(ActionListener<NetworkEvent> a) | Removes the given listener |
public void addResponseCodeListener(ActionListener<NetworkEvent> a) | Adds a listener that would be notified on the CodenameOne thread of a response code that is not a 200 (OK) or 301/2 (redirect) response code. |
public void addExceptionListener(ActionListener<NetworkEvent> a) | Adds a listener that would be notified on the CodenameOne thread of an exception in this connection request |
public void removeResponseCodeListener(ActionListener<NetworkEvent> a) | Removes the given listener |
public void removeExceptionListener(ActionListener<NetworkEvent> a) | Removes the given listener |
protected boolean hasResponseListeners() | Returns true if someone is listening to action response events, this is useful so we can decide whether to bother collecting data for an event in some cases since building the event object might be memory/CPU intensive. |
protected void fireResponseListener(ActionEvent ev) | Fires the response event to the listeners on this connection |
public boolean isDuplicateSupported() | Indicates whether this connection request supports duplicate entries in the request queue |
public void setDuplicateSupported(boolean duplicateSupported) | Indicates whether this connection request supports duplicate entries in the request queue |
public int hashCode() | Returns a hash code value for the object. |
public boolean equals(Object o) | Indicates whether some other object is “equal to” this one. |
protected void validate() | Validates that the request has the required information before being added to the queue e.g. checks if the URL is null. |
public Dialog getDisposeOnCompletion() | A dialog that will be seamlessly disposed once the given request has been completed |
public void setDisposeOnCompletion(Dialog disposeOnCompletion) | A dialog that will be seamlessly disposed once the given request has been completed |
public Dialog getShowOnInit() | This dialog will be shown when this request enters the network queue |
public void setShowOnInit(Dialog showOnInit) | This dialog will be shown when this request enters the network queue |
public int getSilentRetryCount() | Indicates the number of times to silently retry a connection that failed before prompting |
public void setSilentRetryCount(int silentRetryCount) | Indicates the number of times to silently retry a connection that failed before prompting |
public boolean isFailSilently() | Indicates that we are uninterested in error handling |
public void setFailSilently(boolean failSilently) | Indicates that we are uninterested in error handling |
public boolean isReadResponseForErrors() | When set to true the read response code will happen even for error codes such as 400 and 500 |
public void setReadResponseForErrors(boolean readResponseForErrors) | When set to true the read response code will happen even for error codes such as 400 and 500 |
public String getResponseContentType() | Returns the content type from the response headers |
public boolean isRedirecting() | Returns true if this request is been redirected to a different url |
public String getDestinationFile() | When set to a none null string saves the response to file system under this file name |
public void setDestinationFile(String destinationFile) | When set to a none null string saves the response to file system under this file name |
public String getDestinationStorage() | When set to a none null string saves the response to storage under this file name |
public void setDestinationStorage(String destinationStorage) | When set to a none null string saves the response to storage under this file name |
public boolean isCookiesEnabled() | |
public void setCookiesEnabled(boolean cookiesEnabled) | |
public void setChunkedStreamingMode(int chunklen) | This method is used to enable streaming of a HTTP request body without internal buffering, when the content length is not known in advance. |
public void downloadImageToStorage(String storageFile, SuccessCallback<Image> onSuccess, FailureCallback<Image> onFail, boolean useCache) | Downloads an image to a specified storage file asynchronously and calls the onSuccessCallback with the resulting image. |
public AsyncResource<Image> downloadImageToStorage(String storageFile) | Downloads an image to a specified storage file asynchronously returning an AsyncResource that resolves to the resulting image.. |
public AsyncResource<Image> downloadImageToStorage(String storageFile, boolean useCache) | Downloads an image to a specified storage file asynchronously returning an AsyncResource that resolves to the resulting image.. |
public void downloadImageToStorage(String storageFile, SuccessCallback<Image> onSuccess, boolean useCache) | Downloads an image to a specified storage file asynchronously and calls the onSuccessCallback with the resulting image. |
public void downloadImageToStorage(String storageFile, SuccessCallback<Image> onSuccess) | Downloads an image to a specified storage file asynchronously and calls the onSuccessCallback with the resulting image. |
public void downloadImageToStorage(String storageFile, SuccessCallback<Image> onSuccess, FailureCallback<Image> onFail) | Downloads an image to a specified storage file asynchronously and calls the onSuccessCallback with the resulting image. |
public AsyncResource<Image> downloadImageToFileSystem(String file, boolean useCache) | Downloads an image to a the file system asynchronously returning an AsyncResource object that resolves to the loaded image.. |
public AsyncResource<Image> downloadImageToFileSystem(String file) | Downloads an image to the file system asynchronously returning an AsyncResource object that resolves to the loaded image.. |
public void downloadImageToFileSystem(String file, SuccessCallback<Image> onSuccess, FailureCallback<Image> onFail, boolean useCache) | Downloads an image to a the file system asynchronously and calls the onSuccessCallback with the resulting image. |
public void downloadImageToFileSystem(String file, SuccessCallback<Image> onSuccess, boolean useCache) | Downloads an image to a the file system asynchronously and calls the onSuccessCallback with the resulting image. |
public void downloadImageToFileSystem(String file, SuccessCallback<Image> onSuccess) | Downloads an image to a the file system asynchronously and calls the onSuccessCallback with the resulting image. |
public void downloadImageToFileSystem(String file, SuccessCallback<Image> onSuccess, FailureCallback<Image> onFail) | Downloads an image to a the file system asynchronously and calls the onSuccessCallback with the resulting image. |
public String getRequestBody() | The request body can be used instead of arguments to pass JSON data to a restful request, it can’t be used in a get request and will fail if you have arguments |
public void setRequestBody(String requestBody) | The request body can be used instead of arguments to pass JSON data to a restful request, it can’t be used in a get request and will fail if you have arguments. |
public void setRequestBody(Data data) | The request body can be used instead of arguments to pass JSON data to a restful request, it can’t be used in a get request and will fail if you have arguments. |
public Data getRequestBodyData() | The request body can be used instead of arguments to pass JSON data to a restful request, it can’t be used in a get request and will fail if you have arguments |
public String getResponseErrorMessage() | Returns error message associated with an error response code |
Inherited methods
Field details
PRIORITY_CRITICAL
public static final byte PRIORITY_CRITICAL = 100PRIORITY_HIGH
public static final byte PRIORITY_HIGH = 80PRIORITY_NORMAL
public static final byte PRIORITY_NORMAL = 50PRIORITY_LOW
public static final byte PRIORITY_LOW = 30PRIORITY_REDUNDANT
public static final byte PRIORITY_REDUNDANT = 0Constructor details
ConnectionRequest
public ConnectionRequest()ConnectionRequest
public ConnectionRequest(String url)Parameters
urlString- the url
ConnectionRequest
public ConnectionRequest(String url, boolean post)Parameters
urlString- the url
postboolean- whether the request is a post url or a get URL
Method details
getDefaultCacheMode
public static ConnectionRequest.CachingMode getDefaultCacheMode()#getCacheMode()Returns
setDefaultCacheMode
public static void setDefaultCacheMode(ConnectionRequest.CachingMode aDefaultCacheMode)#getCacheMode()Parameters
aDefaultCacheModeConnectionRequest.CachingMode- the defaultCacheMode to set
isReadResponseForErrorsDefault
public static boolean isReadResponseForErrorsDefault()#isReadResponseForErrors()Returns
setReadResponseForErrorsDefault
public static void setReadResponseForErrorsDefault(boolean aReadResponseForErrorsDefault)#setReadResponseForErrors(boolean)Parameters
aReadResponseForErrorsDefaultboolean- the readResponseForErrorsDefault to set
isHandleErrorCodesInGlobalErrorHandler
public static boolean isHandleErrorCodesInGlobalErrorHandler()NetworkManager should receive errors for response code as wellReturns
setHandleErrorCodesInGlobalErrorHandler
public static void setHandleErrorCodesInGlobalErrorHandler(boolean aHandleErrorCodesInGlobalErrorHandler)NetworkManager should receive errors for response code as wellParameters
aHandleErrorCodesInGlobalErrorHandlerboolean- the handleErrorCodesInGlobalErrorHandler to set
getCookieHeader
public static String getCookieHeader()Returns
setCookieHeader
public static void setCookieHeader(String aCookieHeader)Parameters
aCookieHeaderString- the cookieHeader to set
isCookiesEnabledDefault
public static boolean isCookiesEnabledDefault()Returns
setCookiesEnabledDefault
public static void setCookiesEnabledDefault(boolean aCookiesEnabledDefault)Parameters
aCookiesEnabledDefaultboolean- the cookiesEnabledDefault to set
isDefaultFollowRedirects
public static boolean isDefaultFollowRedirects()Returns
setDefaultFollowRedirects
public static void setDefaultFollowRedirects(boolean aDefaultFollowRedirects)Parameters
aDefaultFollowRedirectsboolean- the defaultFollowRedirects to set
isReadTimeoutSupported
public static boolean isReadTimeoutSupported()Returns
purgeCacheDirectory
public static void purgeCacheDirectory()
throws IOExceptionThrows
getDefaultUserAgent
public static String getDefaultUserAgent()Returns
setDefaultUserAgent
public static void setDefaultUserAgent(String aDefaultUserAgent)Parameters
aDefaultUserAgentString- the defaultUserAgent to set
setUseNativeCookieStore
public static void setUseNativeCookieStore(boolean b)Indicates whether the native Cookie stores should be used
NOTE: If the platform doesn’t support Native Cookie sharing, then this method will
have no effect. Use #isNativeCookieSharingSupported()} to check if the platform
supports native cookie sharing at runtime.
Parameters
bboolean- true to enable native cookie stores when applicable
isNativeCookieSharingSupported
public static boolean isNativeCookieSharingSupported()Checks if the platform supports sharing cookies between the native components (e.g. BrowserComponent) and ConnectionRequests. Currently only iOS and Android support this.
If the platform does not support native cookie sharing, then methods like #setUseNativeCookieStore(boolean) will
have no effect.
Returns
fetchJSON
public static Map<String, Object> fetchJSON(String url)
throws IOExceptionParameters
urlString- the URL hosing the JSON
Returns
Throws
IOException- in case of an error
fetchJSONAsync
public static AsyncResource<Map<String, Object>> fetchJSONAsync(String url)Parameters
urlString- The URL to fetch.
Returns
getCacheMode
public ConnectionRequest.CachingMode getCacheMode()There are 5 caching modes:
OFFis the default, meaning no caching.SMARTmeans all get requests are cached intelligently and caching is “mostly” seamless.MANUALmeans that the developer is responsible for the actual caching but the system will not do a request on a resource that’s already “fresh”.OFFLINEwill fetch data from the cache and wont try to go to the server. It will generate a 404 error if data isn’t available.OFFLINE_FIRSTworks the same way as offline but if data isn’t available locally it will try to connect to the server.
Returns
setCacheMode
public void setCacheMode(ConnectionRequest.CachingMode cacheMode)There are 5 caching modes:
OFFis the default, meaning no caching.SMARTmeans all get requests are cached intelligently and caching is “mostly” seamless.MANUALmeans that the developer is responsible for the actual caching but the system will not do a request on a resource that’s already “fresh”.OFFLINEwill fetch data from the cache and wont try to go to the server. It will generate a 404 error if data isn’t available.OFFLINE_FIRSTworks the same way as offline but if data isn’t available locally it will try to connect to the server.
Parameters
cacheModeConnectionRequest.CachingMode- the cacheMode to set
isCheckSSLCertificates
public boolean isCheckSSLCertificates()Returns
setCheckSSLCertificates
public void setCheckSSLCertificates(boolean checkSSLCertificates)Parameters
checkSSLCertificatesboolean- the checkSSLCertificates to set
isInsecure
public boolean isInsecure()Returns
setInsecure
public void setInsecure(boolean insecure)getResponseData
public byte[] getResponseData()Returns
getHttpMethod
public String getHttpMethod()Returns
setHttpMethod
public void setHttpMethod(String httpMethod)Parameters
httpMethodString- the http method string
addRequestHeader
public void addRequestHeader(String key, String value)Parameters
keyString- the header key
valueString- the header value
removeRequestHeader
public void removeRequestHeader(String key)Removes a header previously added with addRequestHeader(String, String).
Needed because a redirect reuses the same request object with the same headers: anything scoped to the original host has to be removable before the retry, or it follows the redirect to wherever it points.
removeRequestHeaderIfUnchanged
public void removeRequestHeaderIfUnchanged(String key, String value)Removes a header previously added with addRequestHeader(String, String), but only
while it still holds value.
A layer that decorates a request it does not own – an interceptor attaching a
credential – has to take its header back off before the request is reused for
somewhere else. By name alone that removes whatever is under the name by then, and
the app itself gets a turn in between: onRedirect(String) runs between the
response and the retry, and it is exactly where an app installs the headers the
redirect target needs. If the two pick the same name, removing by name deletes the
app’s credential rather than the decorator’s. The value is what tells them apart.
Parameters
keyString- the header key, matched without regard to case as HTTP requires
valueString- the value the header must still have; anything else is left alone
checkSSLCertificates
protected void checkSSLCertificates(ConnectionRequest.SSLCertificate[] certificates)A callback that can be overridden by subclasses to check the SSL certificates for the server, and kill the connection if they don’t pass muster. This can be used for SSL pinning.
NOTE: This method will only be called if #isCheckSSLCertificates() is true and the platform supports SSL certificates (#canGetSSLCertificates().
WARNING: On iOS it is possible that certificates for a request would not be available even through the platform supports it, and checking certificates are enabled. This could happen if the certificates had been cached by the TLS cache by some network mechanism other than ConnectionRequest (e.g. native code, websockets, etc..). In such cases this method would receive an empty array as a parameter.
This is called after the SSL handshake, but before any data has been sent.
Parameters
certificatesConnectionRequest.SSLCertificate[]- The server’s SSL certificates.
getReadTimeout
public int getReadTimeout()#isReadTimeoutSupported()
is true on this platform. Currently Android, Mac Desktop, Windows Desktop, and Simulator supports read timeouts.Returns
setReadTimeout
public void setReadTimeout(int timeout)#isReadTimeoutSupported()
is true on this platform. Currently Android, Mac Desktop, Windows Desktop, and Simulator supports read timeouts.Parameters
timeoutint- The read timeout. If less than or equal to zero, then there is no timeout.
See also
initConnection
protected void initConnection(Object connection)Parameters
connectionObject- the connection object
getCachedData
protected InputStream getCachedData()
throws IOExceptionCacheMode.MANUAL to provide offline caching. The default
implementation will work as expected in the CacheMode.SMART and CacheMode.OFFLINE_FIRST modes.Returns
Throws
purgeCache
public void purgeCache()cacheUnmodified
protected void cacheUnmodified()
throws IOExceptionThrows
cookieReceived
protected void cookieReceived(Cookie c)Parameters
cCookie- the cookie
cookieSent
protected void cookieSent(Cookie c)Parameters
cCookie- the cookie
initCookieHeader
protected String initCookieHeader(String cookie)Parameters
cookieString- the cookie that the implementation is about to send or null for no cookie
Returns
getResponseCode
public int getResponseCode()Returns
getResposeCode
public int getResposeCode()Returns
shouldConvertPostToGetOnRedirect
protected boolean shouldConvertPostToGetOnRedirect()Returns
readHeaders
protected void readHeaders(Object connection)
throws IOExceptionParameters
connectionObject- used when invoking getHeader
Throws
java.io.IOException- thrown on failure
readErrorCodeHeaders
protected void readErrorCodeHeaders(Object connection)
throws IOExceptionParameters
connectionObject- used when invoking getHeader
Throws
java.io.IOException- thrown on failure
getHeader
protected String getHeader(Object connection, String header)
throws IOExceptionParameters
connectionObject- the connection to the network
headerString- the name of the header
Returns
Throws
java.io.IOException- thrown on failure
getHeaders
protected String[] getHeaders(Object connection, String header)
throws IOExceptionParameters
connectionObject- the connection to the network
headerString- the name of the header
Returns
Throws
java.io.IOException- thrown on failure
getHeaderFieldNames
protected String[] getHeaderFieldNames(Object connection)
throws IOExceptionParameters
connectionObject- the connection to the network
Returns
Throws
java.io.IOException- thrown on failure
getYield
protected int getYield()Returns
shouldAutoCloseResponse
protected boolean shouldAutoCloseResponse()Returns
handleIOException
protected void handleIOException(IOException err)Parameters
errIOException- the exception thrown
handleRuntimeException
protected void handleRuntimeException(RuntimeException err)Parameters
errRuntimeException- the exception thrown
handleException
protected void handleException(Exception err)Parameters
errException- the exception thrown
canGetSSLCertificates
public boolean canGetSSLCertificates()Returns
getSSLCertificates
public ConnectionRequest.SSLCertificate[] getSSLCertificates()
throws IOExceptionReturns
Throws
handleErrorResponseCode
protected void handleErrorResponseCode(int code, String message)Parameters
codeint- the response code from the server
messageString- the response message from the server
retry
public void retry()onRedirect
public boolean onRedirect(String url)Parameters
urlString- the url to be redirected
Returns
readResponse
protected void readResponse(InputStream input)
throws IOExceptionParameters
inputInputStream- the input stream containing the response
Throws
IOException- when a read input occurs
postResponse
protected void postResponse()createRequestURL
protected String createRequestURL()Returns
buildRequestBody
protected void buildRequestBody(OutputStream os)
throws IOExceptionParameters
osOutputStream- output stream of the body
Throws
shouldWriteUTFAsGetBytes
protected boolean shouldWriteUTFAsGetBytes()kill
public void kill()shouldStop
protected boolean shouldStop()Returns
isPausable
protected boolean isPausable()Returns
pause
public boolean pause()Returns
resume
public boolean resume()Returns
isPost
public boolean isPost()Returns
setPost
public void setPost(boolean post)Throws
IllegalStateException- if invoked after an addArgument call
addArgument
public void addArgument(String key, byte[] value)Parameters
keyString- the key of the argument
valuebyte[]- the value for the argument
removeArgument
public void removeArgument(String key)Parameters
keyString- the key of the argument no longer used
removeAllArguments
public void removeAllArguments()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 key, String value)Parameters
keyString- the key of the argument
valueString- the value for the argument
addArgumentArray
public void addArgumentArray(String key, String... value)Parameters
keyString- the key of the argument
valueString...- the value for the argument
addArgument
public void addArgument(String key, String[] value)Parameters
keyString- the key of the argument
valueString[]- the value for the argument
addArguments
public void addArguments(String key, String... value)Parameters
keyString- the key of the argument
valueString...- the value for the argument
getContentType
public String getContentType()Returns
setContentType
public void setContentType(String contentType)Parameters
contentTypeString- the contentType to set
isWriteRequest
public boolean isWriteRequest()Returns
setWriteRequest
public void setWriteRequest(boolean writeRequest)Parameters
writeRequestboolean- the writeRequest to set
isReadRequest
public boolean isReadRequest()Returns
setReadRequest
public void setReadRequest(boolean readRequest)Parameters
readRequestboolean- the readRequest to set
isPaused
protected boolean isPaused()Returns
setPaused
protected void setPaused(boolean paused)Parameters
pausedboolean- the paused to set
isKilled
protected boolean isKilled()Returns
setKilled
protected void setKilled(boolean killed)Parameters
killedboolean- the killed to set
getPriority
public byte getPriority()Returns
setPriority
public void setPriority(byte priority)Parameters
prioritybyte- the priority to set
getUserAgent
public String getUserAgent()Returns
setUserAgent
public void setUserAgent(String userAgent)Parameters
userAgentString- the userAgent to set
isFollowRedirects
public boolean isFollowRedirects()Returns
setFollowRedirects
public void setFollowRedirects(boolean followRedirects)Parameters
followRedirectsboolean- the followRedirects to set
getTimeout
public int getTimeout()Returns
setTimeout
public void setTimeout(int timeout)Parameters
timeoutint- the timeout to set
getContentLength
public int getContentLength()Returns
ioStreamUpdate
public void ioStreamUpdate(Object source, int bytes)Parameters
sourceObject- the source stream which can be either an input stream or an output stream
bytesint- the number of bytes read or written
getUrl
public String getUrl()Returns
setUrl
public void setUrl(String url)Parameters
urlString- the url to set
addResponseListener
public void addResponseListener(ActionListener<NetworkEvent> a)Parameters
aActionListener<NetworkEvent>- listener
removeResponseListener
public void removeResponseListener(ActionListener<NetworkEvent> a)Parameters
aActionListener<NetworkEvent>- listener
addResponseCodeListener
public void addResponseCodeListener(ActionListener<NetworkEvent> a)Parameters
aActionListener<NetworkEvent>- listener
addExceptionListener
public void addExceptionListener(ActionListener<NetworkEvent> a)Parameters
aActionListener<NetworkEvent>- listener
removeResponseCodeListener
public void removeResponseCodeListener(ActionListener<NetworkEvent> a)Parameters
aActionListener<NetworkEvent>- listener
removeExceptionListener
public void removeExceptionListener(ActionListener<NetworkEvent> a)Parameters
aActionListener<NetworkEvent>- listener
hasResponseListeners
protected boolean hasResponseListeners()Returns
fireResponseListener
protected void fireResponseListener(ActionEvent ev)Parameters
evActionEvent- the event to fire
isDuplicateSupported
public boolean isDuplicateSupported()Returns
setDuplicateSupported
public void setDuplicateSupported(boolean duplicateSupported)Parameters
duplicateSupportedboolean- the duplicateSupported to set
hashCode
public int hashCode()equals
public boolean equals(Object o)validate
protected void validate()getDisposeOnCompletion
public Dialog getDisposeOnCompletion()Returns
setDisposeOnCompletion
public void setDisposeOnCompletion(Dialog disposeOnCompletion)Parameters
disposeOnCompletionDialog- the disposeOnCompletion to set
getShowOnInit
public Dialog getShowOnInit()Returns
setShowOnInit
public void setShowOnInit(Dialog showOnInit)Parameters
showOnInitDialog- the showOnInit to set
getSilentRetryCount
public int getSilentRetryCount()Returns
setSilentRetryCount
public void setSilentRetryCount(int silentRetryCount)Parameters
silentRetryCountint- the silentRetryCount to set
isFailSilently
public boolean isFailSilently()Returns
setFailSilently
public void setFailSilently(boolean failSilently)Parameters
failSilentlyboolean- the failSilently to set
isReadResponseForErrors
public boolean isReadResponseForErrors()Returns
setReadResponseForErrors
public void setReadResponseForErrors(boolean readResponseForErrors)Parameters
readResponseForErrorsboolean- the readResponseForErrors to set
getResponseContentType
public String getResponseContentType()Returns
isRedirecting
public boolean isRedirecting()Returns
getDestinationFile
public String getDestinationFile()Returns
setDestinationFile
public void setDestinationFile(String destinationFile)Parameters
destinationFileString- the destinationFile to set
getDestinationStorage
public String getDestinationStorage()Returns
setDestinationStorage
public void setDestinationStorage(String destinationStorage)Parameters
destinationStorageString- the destinationStorage to set
isCookiesEnabled
public boolean isCookiesEnabled()Returns
setCookiesEnabled
public void setCookiesEnabled(boolean cookiesEnabled)Parameters
cookiesEnabledboolean- the cookiesEnabled to set
setChunkedStreamingMode
public void setChunkedStreamingMode(int chunklen)Parameters
chunklenint- The number of bytes to write in each chunk. If chunklen is zero a default value will be used.
downloadImageToStorage
public void downloadImageToStorage(String storageFile, SuccessCallback<Image> onSuccess, FailureCallback<Image> onFail, boolean useCache)Parameters
storageFileString- The storage file where the file should be saved.
onSuccessSuccessCallback<Image>- Callback called if the image is successfully loaded.
onFailFailureCallback<Image>- Callback called if we fail to load the image.
useCacheboolean- If true, then this will first check the storage to see if the image is already downloaded.
downloadImageToStorage
public AsyncResource<Image> downloadImageToStorage(String storageFile)Parameters
storageFileString- The storage file where the file should be saved.
Returns
downloadImageToStorage
public AsyncResource<Image> downloadImageToStorage(String storageFile, boolean useCache)Parameters
storageFileString- The storage file where the file should be saved.
useCacheboolean- If true, then this will first check the storage to see if the image is already downloaded.
Returns
downloadImageToStorage
public void downloadImageToStorage(String storageFile, SuccessCallback<Image> onSuccess, boolean useCache)Parameters
storageFileString- The storage file where the file should be saved.
onSuccessSuccessCallback<Image>- Callback called if the image is successfully loaded.
useCacheboolean- If true, then this will first check the storage to see if the image is already downloaded.
downloadImageToStorage
public void downloadImageToStorage(String storageFile, SuccessCallback<Image> onSuccess)Parameters
storageFileString- The storage file where the file should be saved.
onSuccessSuccessCallback<Image>- Callback called if the image is successfully loaded.
downloadImageToStorage
public void downloadImageToStorage(String storageFile, SuccessCallback<Image> onSuccess, FailureCallback<Image> onFail)Parameters
storageFileString- The storage file where the file should be saved.
onSuccessSuccessCallback<Image>- Callback called if the image is successfully loaded.
onFailFailureCallback<Image>- Not documented.
downloadImageToFileSystem
public AsyncResource<Image> downloadImageToFileSystem(String file, boolean useCache)Parameters
fileString- The storage file where the file should be saved.
useCacheboolean- If true, then this will first check the storage to see if the image is already downloaded.
Returns
downloadImageToFileSystem
public AsyncResource<Image> downloadImageToFileSystem(String file)boolean)
with true as the 2nd parameter.Parameters
fileString- The storage file where the file should be saved.
Returns
downloadImageToFileSystem
public void downloadImageToFileSystem(String file, SuccessCallback<Image> onSuccess, FailureCallback<Image> onFail, boolean useCache)Parameters
fileString- The storage file where the file should be saved.
onSuccessSuccessCallback<Image>- Callback called if the image is successfully loaded.
onFailFailureCallback<Image>- Callback called if we fail to load the image.
useCacheboolean- If true, then this will first check the storage to see if the image is already downloaded.
downloadImageToFileSystem
public void downloadImageToFileSystem(String file, SuccessCallback<Image> onSuccess, boolean useCache)Parameters
fileString- The storage file where the file should be saved.
onSuccessSuccessCallback<Image>- Callback called if the image is successfully loaded.
useCacheboolean- If true, then this will first check the storage to see if the image is already downloaded.
downloadImageToFileSystem
public void downloadImageToFileSystem(String file, SuccessCallback<Image> onSuccess)Parameters
fileString- The storage file where the file should be saved.
onSuccessSuccessCallback<Image>- Callback called if the image is successfully loaded.
downloadImageToFileSystem
public void downloadImageToFileSystem(String file, SuccessCallback<Image> onSuccess, FailureCallback<Image> onFail)Parameters
fileString- The storage file where the file should be saved.
onSuccessSuccessCallback<Image>- Callback called if the image is successfully loaded.
onFailFailureCallback<Image>- Callback called if the image fails to load.
getRequestBody
public String getRequestBody()Returns
setRequestBody
public void setRequestBody(String requestBody)The request body can be used instead of arguments to pass JSON data to a restful request, it can’t be used in a get request and will fail if you have arguments.
Notice that invoking this method blocks the #buildRequestBody(java.io.OutputStream) method
callback.
Parameters
requestBodyString- a string to pass in the post body
setRequestBody
public void setRequestBody(Data data)The request body can be used instead of arguments to pass JSON data to a restful request, it can’t be used in a get request and will fail if you have arguments.
Notice that invoking this method blocks the #buildRequestBody(java.io.OutputStream) method
callback.
Parameters
dataData- a data to pass in the post body
getRequestBodyData
public Data getRequestBodyData()Returns
getResponseErrorMessage
public String getResponseErrorMessage()