public interface IHttpPost
extends java.lang.AutoCloseable
Parameters are sent as if they would be part of an HTML form. The content-type ("Content-Type" request property) of the request will be set to
"application/x-www-form-urlencoded;charset=UTF-8".
Its usefulness includes -but is not limited to- uploading/downloading files without having to use Multi-part requests. The following examples will demonstrate these.
Instances can be acquired by IFactory.newHttpPost(java.net.URL, java.util.Map).
Example #1: Upload a file encoded with Base64:
String url = "http://some.site.com/upload"; Path file = Paths.get( "c:/downloads/mine.txt" ); Map< String, String > paramsMap = new HashMap< String, String >(); paramsMap.put( "fileName", file.getFileName().toString() ); try { paramsMap.put( "fileBase64", utils.toBase64String( Files.readAllBytes( file ) ) ); } catch ( IOException ie ) { } // Add other parameters you need... paramsMap.put( "someOtherThing", "some other value" ); try ( IHttpPost httpPost = factory.newHttpPost( url, paramsMap ) ) { if ( httpPost.connect() ) { if ( httpPost.doPost() ) logger.info( "File sent successfully, server response: " + httpPost.getResponse() ); else logger.error( "Failed to send file!" ); } else logger.error( "Failed to connect!" ); } catch ( Exception e ) { logger.error( "Unexpected file upload error!", e ); }
Example #2: Download a file from a server:
String url = "http://some.site.com/download"; Map< String, String > paramsMap = new HashMap< String, String >(); String fileName = "somefile.txt"; paramsMap.put( "fileName", fileName ); // Add other parameters you need... paramsMap.put( "userId", "someUserId" ); try ( IHttpPost httpPost = factory.newHttpPost( url, paramsMap ) ) { if ( httpPost.connect() ) { if ( httpPost.doPost() ) { // Note: we could simply acquire a suitable file provider by: // factory.newSimpleFileProvider( Paths.get( "c:/downloads", fileName ), null ); // but this is to demonstrate the use and possibilities of IFileProvider boolean result = httpPost.saveAttachmentToFile( new IFileProvider() { public Path getFile( HttpURLConnection httpUrlConnection ) { Path file = Paths.get( "c:/downloads", fileName ); logger.info( "Saving file to: " + file ); return file; } public Long getLastModified( HttpURLConnection httpUrlConnection ) { // We assume here that the server sends the file last modified value as a header field named "X-file-date": String fileDateString = httpUrlConnection.getHeaderField( "X-file-date" ); return fileDateString == null ? null : Long.valueOf( fileDateString ); } } ); if ( result ) logger.info( "Attachment saved successfully to file: " + file ); } else logger.error( "Failed to send request!" ); } else logger.error( "Failed to connect!" ); } catch ( Exception e ) { logger.error( "Unexpected file download error!", e ); }
IFactory.newHttpPost(java.net.URL, java.util.Map)| Modifier and Type | Field and Description |
|---|---|
static java.lang.String |
DEFAULT_CHARSET
Default charset to be used.
|
| Modifier and Type | Method and Description |
|---|---|
void |
close()
Closes this
IHttpPost, releases all allocated resources. |
boolean |
connect()
Connects to the provided URL.
|
boolean |
connect(java.lang.Runnable beforeConnectionConnectTask)
Connects to the provided URL.
|
boolean |
doPost()
Posts the parameters to the server.
|
java.net.HttpURLConnection |
getConnection()
Returns the underlying
HttpURLConnection. |
java.lang.String |
getRequestCharset()
Returns the charset of the request.
|
java.lang.String |
getResponse()
Gets the response from the server.
|
java.util.List<java.lang.String> |
getResponseLines()
Gets the response from the server as a list of lines.
|
int |
getServerResponseCode()
Returns the HTTP response code of the server.
|
java.lang.String |
getServerResponseMessage()
Returns the HTTP response message of the server.
|
State |
getState()
Returns the internal state of the connection/communication.
|
boolean |
isInternalStateCheckingEnabled()
Tells if internal state checking is enabled.
|
boolean |
isServerResponseOk()
Tells if the the HTTP response code is OK (HTTP 200).
|
boolean |
saveAttachmentToFile(IFileProvider fileProvider,
byte[]... buffer)
Saves the attachment of the response, the content is treated as
application/octet-stream. |
void |
setInternalStateCheckingEnabled(boolean enabled)
Sets whether internal state checking should be performed.
|
void |
setRequestCharset(java.lang.String charset)
Sets the charset of the request.
|
void |
setRequestProperty(java.lang.String key,
java.lang.String value)
Sets a request property.
|
static final java.lang.String DEFAULT_CHARSET
void setInternalStateCheckingEnabled(boolean enabled)
You may want to disable internal state checking if you want to tweak the HttpURLConnection.
enabled - the internal state checking value to be setboolean isInternalStateCheckingEnabled()
State getState()
void setRequestCharset(java.lang.String charset)
throws java.lang.IllegalStateException
This will set the request property "Accept-Charset" to charset.
It must be called before connect(). If charset is not set, the DEFAULT_CHARSET will be used.
charset - charset of the request to be setjava.lang.IllegalStateException - if internal state checking is enabled and the internal state is not State.NOT_CONNECTEDjava.lang.String getRequestCharset()
DEFAULT_CHARSET.void setRequestProperty(java.lang.String key,
java.lang.String value)
throws java.lang.IllegalStateException
The properties will be passed to the underlying HttpURLConnection before it's connect() method is called.
It must be called before connect().
key - the property keyvalue - the property valuejava.lang.IllegalStateException - if internal state checking is enabled and the internal state is not State.NOT_CONNECTEDjava.net.HttpURLConnection getConnection()
HttpURLConnection.
This method may return null if called before connect() or if called when connect() returned false.
HttpURLConnectionboolean connect()
throws java.lang.IllegalStateException
Only one connect method (connect() or connect(Runnable)) can be called and only once.
java.lang.IllegalStateException - if internal state checking is enabled and the internal state is not State.NOT_CONNECTEDconnect(Runnable)boolean connect(java.lang.Runnable beforeConnectionConnectTask)
throws java.lang.IllegalStateException
Only one connect method (connect() or connect(Runnable)) can be called and only once.
beforeConnectionConnectTask - task to be executed right before calling URLConnection.connect()java.lang.IllegalStateException - if internal state checking is enabled and the internal state is not State.NOT_CONNECTEDconnect()boolean doPost()
throws java.lang.IllegalStateException
The parameters will be encoded using the charset set by setRequestCharset(String) (defaults to "UTF-8" ).
Can only be called if connect() returned true.
java.lang.IllegalStateException - if internal state checking is enabled and the internal state is not State.CONNECTEDboolean isServerResponseOk()
throws java.lang.IllegalStateException
java.lang.IllegalStateException - if internal state checking is enabled and doPost() has not been called or close() has been calledgetServerResponseCode(),
getServerResponseMessage()int getServerResponseCode()
throws java.lang.IllegalStateException
java.lang.IllegalStateException - if internal state checking is enabled and doPost() has not been called or close() has been calledisServerResponseOk(),
getServerResponseMessage()java.lang.String getServerResponseMessage()
throws java.lang.IllegalStateException
java.lang.IllegalStateException - if internal state checking is enabled and doPost() has not been called or close() has been calledisServerResponseOk(),
getServerResponseCode()java.lang.String getResponse()
throws java.lang.IllegalStateException
Can only be called after doPost().
If the server returned an error, this will return the error page provided by the server.
null if error occurredjava.lang.IllegalStateException - if internal state checking is enabled and the internal state is not State.REQUEST_SENTgetResponseLines(),
saveAttachmentToFile(IFileProvider, byte[][])java.util.List<java.lang.String> getResponseLines()
throws java.lang.IllegalStateException
Can only be called after doPost().
If the server returned an error, this will return the error page provided by the server.
null if error occurredjava.lang.IllegalStateException - if internal state checking is enabled and the internal state is not State.REQUEST_SENTgetResponse(),
saveAttachmentToFile(IFileProvider, byte[][])boolean saveAttachmentToFile(IFileProvider fileProvider, byte[]... buffer) throws java.lang.IllegalStateException
application/octet-stream.
Can only be called if doPost() returned true.
A IFileProvider is used to get a file to save the attachment to.
fileProvider - file provider to specify a file to save tobuffer - optional buffer to use for IO read/write operationsjava.lang.IllegalStateException - if internal state checking is enabled and the internal state is not State.REQUEST_SENTIFileProvider,
IFactory.newSimpleFileProvider(java.nio.file.Path, Long),
getResponse(),
getResponseLines()void close()
IHttpPost, releases all allocated resources.close in interface java.lang.AutoCloseable
This API documentation is public and is intended for / allowed to be used by anyone.
Scelight home page: https://sites.google.com/site/scelight/
Scelight is a trademark of András Belicza. Copyright © András Belicza, 2013-2015. All rights reserved.