public class HTTPClient
extends java.lang.Object
// initialization
StdoutLogAdapter logAdapter = new StdoutLogAdapter(); // you may implement your own log adapter
logAdapter.init(null);
logAdapter.setLogLevel(LogAdapterInterface.LOG_DEBUG);
HTTPClient httpClient = new HTTPClient(logAdapter);
httpClient.setHTTPProcessingTimeout(30000);
// --------------------
// synchronous programming example 1
HTTPRequest httpRequest = httpClient.newRequest("GET", "https://www.dkfqa.com");
HTTPResponse httpResponse = httpClient.sendSyncRequest(httpRequest);
if (httpResponse.getHttpRequest().hasErrorException()) {
System.out.println("HTTP request failed: " + httpResponse.getHttpRequest().getErrorException());
}
else {
System.out.println(httpResponse.getHttpResponseContent().getContentAsString());
}
// synchronous programming example 2
HTTPRequest httpRequest = httpClient.newRequest("GET", "https://www.dkfqa.com");
long requestId = httpClient.sendAsyncRequest(httpRequest);
HTTPResponse httpResponse = httpClient.waitAndGetResponse(requestId);
if (httpResponse.getHttpRequest().hasErrorException()) {
System.out.println("HTTP request failed: " + httpResponse.getHttpRequest().getErrorException());
}
else {
System.out.println(httpResponse.getHttpResponseContent().getContentAsString());
}
// synchronous programming example 3
HTTPRequest httpRequest1 = httpClient.newRequest("GET", "https://www.dkfqa.com");
httpClient.sendAsyncRequest(httpRequest1);
HTTPRequest httpRequest2 = httpClient.newRequest("GET", "https://www.dkfqa.com/content/logo183x32.gif");
httpClient.sendAsyncRequest(httpRequest2);
httpClient.waitAllResponses();
HTTPResponse httpResponse = httpClient.getNextResponse();
while (httpResponse != null) {
if (httpResponse.getHttpRequest().hasErrorException()) {
System.out.println("HTTP request failed: " + httpResponse.getHttpRequest().getErrorException());
}
else {
System.out.println(httpResponse.getHttpResponseContent().getContentAsString());
}
httpResponse = httpClient.getNextResponse();
}
// --------------------
// asynchronous programming example
// the (implemented) interface for instantly processing the received HTTP responses
public class MyAsyncResponseHandler implements HTTPClientAsyncResponseHandler {
public void onAsyncResponse(HTTPResponse httpResponse) throws Exception {
HTTPRequest httpRequest = httpResponse.getHttpRequest();
if (httpRequest.hasErrorException()) {
System.out.println("HTTP request failed for " + httpRequest.getUrl() + " | " + httpRequest.getErrorException());
}
else {
System.out.println("Receive HTTP response for request ID " + httpRequest.getId() + " = " + httpResponse.getHttpResponseHeader().getHttpStatusCode() + " " + httpResponse.getHttpResponseHeader().getReceivedHttpStatusText());
}
}
}
httpClient.setAsyncResponseHandler(new MyAsyncResponseHandler()); // set the (implemented) interface for instantly processing the received HTTP responses
HTTPRequest httpRequestA = httpClient.newRequest("GET", "https://www.dkfqa.com");
long requestIdA = httpClient.sendAsyncRequest(httpRequestA);
HTTPRequest httpRequestB = httpClient.newRequest("GET", "https://www.dkfqa.com/content/logo183x32.gif");
long requestIdB = httpClient.sendAsyncRequest(httpRequestB);
httpClient.waitAllResponses(); // synchronisation point
// --------------------
// free all internal resources
httpClient.closeAbort();
| Constructor and Description |
|---|
HTTPClient(LogAdapterInterface logAdapter)
Create a new instance with 4 processing threads.
|
HTTPClient(LogAdapterInterface logAdapter,
int numProcessingThreads)
Create a new instance with a specific number processing threads.
|
| Modifier and Type | Method and Description |
|---|---|
void |
addClientAuthKeyManagers(java.lang.String serverHost,
int serverPort,
javax.net.ssl.KeyManager[] clientAuthKeyManagers)
Add SSL key managers for client authentication, for a particular HTTPS host and port.
|
void |
addGlobalRequestHeaderField(java.lang.String headerFieldName,
java.lang.String headerFieldValue)
Add a global request header field which is applied to all HTTP requests.
|
void |
clearConnectionPool()
Close and remove all network connections from the connection pool.
|
void |
clearSession()
Close and remove all network connections from the connection pool and remove all cookies.
|
void |
clearSession(boolean clearStatisticalData)
Close and remove all network connections from the connection pool and remove all cookies.
|
void |
closeAbort()
Free all internal resources and close all connections of the HTTPClient.
|
void |
dumpConnectionPoolToStdout()
For debug purposes only, dump the network connection pool to stdout.
|
void |
dumpProcessingPoolToStdout()
For debug purposes only, dump the HTTP client processing pool to stdout.
|
HTTPConnectionStatistic |
getConnectionStatistic()
Performance data, get the statistic of the network connections used by the HTTPClient.
|
HTTPCookieHandler |
getCookieHandler()
Get access to the cookie handler of the HTTP client.
|
java.util.List<HTTPHeaderField> |
getGlobalRequestHeaderFieldList()
Get a list of all global request header fields.
|
int |
getHTTPProcessingTimeout()
Get the default value for the processing timeout per URL at HTTP level.
|
long |
getMaxHTTPResponseSize()
Get the maximal size of a HTTP response in bytes.
|
long |
getMaxStoredHTTPResponseContentLength()
Get the maximal length of a stored HTTP response content in bytes.
|
HTTPResponse |
getNextResponse()
Get the next HTTP response of all completed HTTP requests.
|
int |
getNumOutstandingRequest()
Performance data, get the number of currently outstanding requests (= number of not yet completed, pending requests).
|
HTTPResponse |
getResponse(long httpRequestId)
Get the HTTP response for a particular HTTP request.
|
int |
getSSLHandshakeTimeout()
Get the SSL handshake timeout.
|
int |
getTCPConnectTimeout()
Get the TCP connect timeout.
|
long |
getTotalBytesReceived()
Get the total number of bytes which were received - counted over all ever executed HTTP/S calls.
|
long |
getTotalBytesSent()
Get the total number of bytes which were sent - counted over all ever executed HTTP/S calls.
|
static void |
main(java.lang.String[] args) |
HTTPRequest |
newRequest(java.lang.String httpRequestMethod,
java.lang.String url)
Create a new HTTP request, but don't send it yet.
|
void |
removeAllClientAuthKeyManagers()
Remove all SSL key managers for client authentication.
|
void |
removeAllCookies()
Remove all cookies.
|
void |
removeGlobalRequestHeaderField(java.lang.String headerFieldName)
Remove a global request header field which was previously added by calling addGlobalRequestHeaderField(String headerFieldName, String headerFieldValue).
|
boolean |
resumeSuspendedHTTPRequest(long httpRequestId)
Resume a suspended HTTP request.
|
long |
sendAsyncRequest(HTTPRequest httpRequest)
Send a HTTP request as an asynchronous operation.
|
long |
sendAsyncRequest(HTTPRequest httpRequest,
HTTPRequestAsyncResponseHandler asyncResponseHandler)
Send a HTTP request as an asynchronous operation.
|
HTTPResponse |
sendSyncRequest(HTTPRequest httpRequest)
Send and receive a HTTP request and the HTTPResponse synchronously.
|
void |
setAsyncResponseHandler(HTTPClientAsyncResponseHandler asyncResponseHandler)
Set the (implemented) interface for instantly processing the received HTTP responses.
|
void |
setClientDebugger(HTTPClientDebuggerInterface clientDebugger)
Set a client debugger.
|
void |
setCountTransmitBytesInterfaces(HTTPClientCountBytesSentInterface bytesSentInterface,
HTTPClientCountBytesReceivedInterface bytesReceivedInterface)
Set callback interfaces which are called each time when the HTTP client has sent or received a data fragment to/from a server.
|
void |
setDelayHTTPRequestTimeMillis(long delayHTTPRequestTimeMillis)
Set the additional delay in milliseconds to send HTTP requests to the server(s).
|
void |
setDelayHTTPResponseHeaderTimeMillis(long delayHTTPResponseHeaderTimeMillis)
Set the additional delay in milliseconds to receive HTTP responses headers from the server(s).
|
void |
setHTTPProcessingTimeout(int httpProcessingTimeoutMillis)
Set the default value for the processing timeout per URL at HTTP level.
|
void |
setLimitSSLVersion(java.lang.String limitSSLVersion)
Set/limit the maximal SSL version.
|
void |
setLocalOutboundAddress(java.net.InetAddress localOutboundAddress)
Set or unset a specific outbound IP address.
|
void |
setMaxHTTPResponseSize(long maxHTTPResponseSize)
Set the maximal size of a HTTP response in bytes (default = unlimited).
|
void |
setMaxStoredHTTPResponseContentLength(long maxStoredHTTPResponseContentLength)
Set the maximal length of a stored HTTP response content in bytes.
|
void |
setOverallTimeout(int overallTimeoutMillis)
Set a synthetically calculated overall timeout for the URL calls
The 3 inner timeouts are calculated as follows: At first, the SSL Handshake Timeout is calculated: as 10% of the Overall Timeout but max. |
void |
setSSLHandshakeTimeout(int sslHandshakeTimeoutMillis)
Set the SSL handshake timeout.
|
void |
setTCPConnectTimeout(int tcpConnectTimeoutMillis)
Set the TCP connect timeout.
|
void |
setThrottleHTTPResponseBytesPerSecond(long throttleHTTPResponseBytesPerSecond)
Set (enable) throttling of HTTP responses.
|
void |
setTraceRequestContentTypesSet(java.util.HashSet<java.lang.String> traceRequestContentTypesSet)
Set a set of mime types for which the request content data are written to the log adapter at trace level.
|
void |
setTraceRequestHeader(boolean traceRequestHeader)
Set if HTTP request headers are written the log adapter at trace level.
|
void |
setTraceResponseContentTypesSet(java.util.HashSet<java.lang.String> traceResponseContentTypesSet)
Set a set of mime types for which the response content data are written to the log adapter at trace level.
|
void |
setTraceResponseHeader(boolean traceResponseHeader)
Set if HTTP response headers are written the log adapter at trace level.
|
void |
setTrustManager(javax.net.ssl.TrustManager[] trustManagers)
Set a specific SSL X509 trust manager, used to validate the certificate chain received from a HTTPS server during the SSL handshake.
|
void |
waitAllResponses()
Wait until all HTTP requests are completed.
|
HTTPResponse |
waitAndGetResponse(long httpRequestId)
Wait until a particular HTTP request is completed and get the corresponding HTTP response.
|
void |
waitResponse(long httpRequestId)
Wait until a particular HTTP request is completed.
|
public HTTPClient(LogAdapterInterface logAdapter)
logAdapter - the log adapter for this instance, or null if logging is disabledpublic HTTPClient(LogAdapterInterface logAdapter, int numProcessingThreads)
logAdapter - the log adapter for this instance, or null if logging is disablednumProcessingThreads - the number processing threads, valid range = 1..64java.lang.IllegalArgumentException - if the number processing threads is out of the valid rangepublic void setAsyncResponseHandler(HTTPClientAsyncResponseHandler asyncResponseHandler)
asyncResponseHandler - the (implemented) interface for instantly processing the received HTTP responseswaitAndGetResponse(long),
waitResponse(long),
getResponse(long),
getNextResponse(),
waitAllResponses()public void addGlobalRequestHeaderField(java.lang.String headerFieldName,
java.lang.String headerFieldValue)
headerFieldName - the name of the request header fieldheaderFieldValue - the value of the request header fieldremoveGlobalRequestHeaderField(String),
getGlobalRequestHeaderFieldList()public void removeGlobalRequestHeaderField(java.lang.String headerFieldName)
headerFieldName - the name of the request header fieldaddGlobalRequestHeaderField(String, String),
getGlobalRequestHeaderFieldList()public java.util.List<HTTPHeaderField> getGlobalRequestHeaderFieldList()
addGlobalRequestHeaderField(String, String),
removeGlobalRequestHeaderField(String)public void setLocalOutboundAddress(java.net.InetAddress localOutboundAddress)
localOutboundAddress - the specific outbound IP address, or null = use default outbound IP addresspublic void setLimitSSLVersion(java.lang.String limitSSLVersion)
limitSSLVersion - the maximal SSL versionpublic void setTrustManager(javax.net.ssl.TrustManager[] trustManagers)
trustManagers - the specific X509 trust managerpublic void addClientAuthKeyManagers(java.lang.String serverHost,
int serverPort,
javax.net.ssl.KeyManager[] clientAuthKeyManagers)
serverHost - the server name or IP addressserverPort - the server TCP/IP portclientAuthKeyManagers - the key managers for SSL client authenticationLoadPKCS12Certificate,
LoadPKCS12Certificate.getKeyManagers()public void removeAllClientAuthKeyManagers()
public void setOverallTimeout(int overallTimeoutMillis)
overallTimeoutMillis - the overall HTTP call timeout in milliseconds, not less than 10000 msjava.lang.IllegalArgumentException - if the overall HTTP call timeout is less than 10000 mssetTCPConnectTimeout(int),
setSSLHandshakeTimeout(int),
setHTTPProcessingTimeout(int)public void setTCPConnectTimeout(int tcpConnectTimeoutMillis)
tcpConnectTimeoutMillis - the TCP connect timeout in millisecondspublic int getTCPConnectTimeout()
public void setSSLHandshakeTimeout(int sslHandshakeTimeoutMillis)
sslHandshakeTimeoutMillis - the SSL handshake timeout in millisecondspublic int getSSLHandshakeTimeout()
public void setHTTPProcessingTimeout(int httpProcessingTimeoutMillis)
httpProcessingTimeoutMillis - the processing timeout per URL at HTTP level in millisecondsHTTPRequest.setRequestSpecificProcessingTimeoutMillis(long)public int getHTTPProcessingTimeout()
public void setMaxHTTPResponseSize(long maxHTTPResponseSize)
maxHTTPResponseSize - the maximal size of a HTTP response in bytes, or -1 = unlimitedHTTPResponseTooLargeExceptionpublic long getMaxHTTPResponseSize()
HTTPResponseTooLargeExceptionpublic void setMaxStoredHTTPResponseContentLength(long maxStoredHTTPResponseContentLength)
maxStoredHTTPResponseContentLength - the maximal length of a stored HTTP response content in bytes, or -1 = unlimitedpublic long getMaxStoredHTTPResponseContentLength()
public void setCountTransmitBytesInterfaces(HTTPClientCountBytesSentInterface bytesSentInterface, HTTPClientCountBytesReceivedInterface bytesReceivedInterface)
bytesSentInterface - called each time when the HTTP client has sent a data fragment to a serverbytesReceivedInterface - called each time when the HTTP client has received a data fragment from a server.public HTTPRequest newRequest(java.lang.String httpRequestMethod, java.lang.String url) throws java.net.MalformedURLException
httpRequestMethod - the HTTP request method. Example: 'GET', 'POST', 'HEAD'url - the full URL. Example: 'https://www.dkfqa.com/test?param1=hello'java.net.MalformedURLException - if the URL is invalidaddGlobalRequestHeaderField(String, String),
HTTPRequest.getId(),
sendAsyncRequest(HTTPRequest)public HTTPResponse sendSyncRequest(HTTPRequest httpRequest) throws java.lang.InterruptedException
httpRequest - the HTTP requestjava.lang.InterruptedException - if the current thread is interruptedpublic long sendAsyncRequest(HTTPRequest httpRequest) throws java.lang.InterruptedException
httpRequest - the HTTP request to sendHTTPClientException - if the request was already sentjava.lang.InterruptedException - if somewhat failspublic long sendAsyncRequest(HTTPRequest httpRequest, HTTPRequestAsyncResponseHandler asyncResponseHandler) throws java.lang.InterruptedException
httpRequest - the HTTP request to sendasyncResponseHandler - the handler which is called when the HTTP response was received (or when the HTTP request was failed)java.lang.InterruptedException - if somewhat failspublic HTTPResponse waitAndGetResponse(long httpRequestId)
httpRequestId - the unique ID of the HTTP requestHTTPClientException - if a HTTPClientAsyncResponseHandler is set.public void waitResponse(long httpRequestId)
httpRequestId - the unique ID of the HTTP requestHTTPClientException - if a HTTPClientAsyncResponseHandler is set.public HTTPResponse getResponse(long httpRequestId)
httpRequestId - the unique ID of the HTTP requestHTTPClientException - if a HTTPClientAsyncResponseHandler is set.waitResponse(long)public void waitAllResponses()
public HTTPResponse getNextResponse()
HTTPClientException - if a HTTPClientAsyncResponseHandler is set.waitAllResponses()public void clearSession()
public void clearSession(boolean clearStatisticalData)
clearStatisticalData - if true then clear also the statistical data of the connection poolgetTotalBytesSent(),
getTotalBytesReceived()public void clearConnectionPool()
public void removeAllCookies()
public void closeAbort()
public HTTPCookieHandler getCookieHandler()
public int getNumOutstandingRequest()
public HTTPConnectionStatistic getConnectionStatistic()
public void dumpConnectionPoolToStdout()
public void dumpProcessingPoolToStdout()
public void setClientDebugger(HTTPClientDebuggerInterface clientDebugger)
clientDebugger - the client debuggerpublic boolean resumeSuspendedHTTPRequest(long httpRequestId)
httpRequestId - the unique, internal HTTP request idjava.lang.NullPointerException - if no client debugger is setsetClientDebugger(HTTPClientDebuggerInterface),
HTTPClientDebuggerInterface.onRequestBeforeSend(HTTPRequest),
HTTPRequest.getId()public void setTraceRequestHeader(boolean traceRequestHeader)
traceRequestHeader - true if HTTP request headers are written the log adapter at trace levelpublic void setTraceResponseHeader(boolean traceResponseHeader)
traceResponseHeader - true if HTTP response headers are written the log adapter at trace levelpublic void setTraceRequestContentTypesSet(java.util.HashSet<java.lang.String> traceRequestContentTypesSet)
traceRequestContentTypesSet - a set of mime types for which the request content data are written to the log adapter at trace levelpublic void setTraceResponseContentTypesSet(java.util.HashSet<java.lang.String> traceResponseContentTypesSet)
traceResponseContentTypesSet - a set of mime types for which the response content data are written to the log adapter at trace levepublic void setDelayHTTPRequestTimeMillis(long delayHTTPRequestTimeMillis)
delayHTTPRequestTimeMillis - the additional delay in milliseconds to send HTTP requests to the server(s), or -1 = no delay (default value)public void setDelayHTTPResponseHeaderTimeMillis(long delayHTTPResponseHeaderTimeMillis)
delayHTTPResponseHeaderTimeMillis - the additional delay in milliseconds to receive HTTP responses headers from the server, or -1 = no delay (default value)public void setThrottleHTTPResponseBytesPerSecond(long throttleHTTPResponseBytesPerSecond)
throttleHTTPResponseBytesPerSecond - the maximum throughput in bytes per second for each HTTP response, or -1 = no throttling (default value).public long getTotalBytesSent()
public long getTotalBytesReceived()
public static void main(java.lang.String[] args)