Class HTTPConnection
- All Implemented Interfaces:
HTTPClientModuleConstants
Using the HTTPClient should be quite simple. First add the import statement '
import HTTPClient.*;' to your file(s). Request can then be sent
using one of the methods Head(), Get(),
Post(), etc in HTTPConnection. These methods all return
an instance of HTTPResponse which has methods for accessing the
response headers (getHeader(), getHeaderAsInt(), etc),
various response info (getStatusCode(),
getReasonLine(), etc) and the reponse data (getData(),
getText(), and getInputStream()). Following are some
examples.
If this is in an applet you can retrieve files from your server as follows:
try {
HTTPConnection con = new HTTPConnection(this);
HTTPResponse rsp = con.Get("/my_file");
if (rsp.getStatusCode() >= 300) {
System.err.println("Received Error: " + rsp.getReasonLine());
System.err.println(rsp.getText());
} else
data = rsp.getData();
rsp = con.Get("/another_file");
if (rsp.getStatusCode() >= 300) {
System.err.println("Received Error: " + rsp.getReasonLine());
System.err.println(rsp.getText());
} else
other_data = rsp.getData();
} catch (IOException ioe) {
System.err.println(ioe.toString());
} catch (ModuleException me) {
System.err.println("Error handling request: " + me.getMessage());
}
This will get the files "/my_file" and "/another_file" and put their contents
into byte[]'s accessible via getData(). Note that you need to
only create a new HTTPConnection when sending a request to a new
server (different host or port); although you may create a new
HTTPConnection for every request to the same server this
not recommended, as various information about the server is
cached after the first request (to optimize subsequent requests) and
persistent connections are used whenever possible.
To POST form data you would use something like this (assuming you have two fields called name and e-mail, whose contents are stored in the variables name and email):
try {
NVPair form_data[] = new NVPair[2];
form_data[0] = new NVPair("name", name);
form_data[1] = new NVPair("e-mail", email);
HTTPConnection con = new HTTPConnection(this);
HTTPResponse rsp = con.Post("/cgi-bin/my_script", form_data);
if (rsp.getStatusCode() >= 300) {
System.err.println("Received Error: " + rsp.getReasonLine());
System.err.println(rsp.getText());
} else
stream = rsp.getInputStream();
} catch (IOException ioe) {
System.err.println(ioe.toString());
} catch (ModuleException me) {
System.err.println("Error handling request: " + me.getMessage());
}
Here the response data is read at leasure via an InputStream
instead of all at once into a byte[].
As another example, if you have a URL you're trying to send a request to you would do something like the following:
try {
URL url = new URL("http://www.mydomain.us/test/my_file");
HTTPConnection con = new HTTPConnection(url);
HTTPResponse rsp = con.Put(url.getFile(), "Hello World");
if (rsp.getStatusCode() >= 300) {
System.err.println("Received Error: " + rsp.getReasonLine());
System.err.println(rsp.getText());
} else
text = rsp.getText();
} catch (IOException ioe) {
System.err.println(ioe.toString());
} catch (ModuleException me) {
System.err.println("Error handling request: " + me.getMessage());
}
There are a whole number of methods for each request type; however the general forms are ([...] means that the enclosed is optional):
- Head ( file [, form-data [, headers ] ] )
- Head ( file [, query [, headers ] ] )
- Get ( file [, form-data [, headers ] ] )
- Get ( file [, query [, headers ] ] )
- Post ( file [, form-data [, headers ] ] )
- Post ( file [, data [, headers ] ] )
- Post ( file [, stream [, headers ] ] )
- Put ( file , data [, headers ] )
- Put ( file , stream [, headers ] )
- Delete ( file [, headers ] )
- Options ( file [, headers [, data] ] )
- Options ( file [, headers [, stream] ] )
- Trace ( file [, headers ] )
- Version:
- 0.3-3 06/05/2001
- Author:
- Ronald Tschal���r
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final intstatic final intstatic final intstatic final intstatic final intstatic final intstatic final intContent delimitersstatic final intpossible http protocols we (might) handlestatic final intsome known http versionsstatic final intstatic final intstatic final intstatic final intstatic final StringThe current version of this package.Fields inherited from interface org.exoplatform.common.http.client.HTTPClientModuleConstants
REQ_CONTINUE, REQ_NEWCON_RST, REQ_NEWCON_SND, REQ_RESPONSE, REQ_RESTART, REQ_RETURN, REQ_SHORTCIRC, RSP_CONTINUE, RSP_NEWCON_REQ, RSP_NEWCON_SND, RSP_REQUEST, RSP_RESTART, RSP_SEND, RSP_SHORTCIRC -
Constructor Summary
ConstructorsConstructorDescriptionHTTPConnection(Applet applet) Constructs a connection to the host from where the applet was loaded.HTTPConnection(String host) Constructs a connection to the specified host on port 80HTTPConnection(String host, int port) Constructs a connection to the specified host on the specified portHTTPConnection(String prot, String host, int port) Constructs a connection to the specified host on the specified port, using the specified protocol (currently only "http" is supported).HTTPConnection(String prot, String host, int port, InetAddress localAddr, int localPort) Constructs a connection to the specified host on the specified port, using the specified protocol (currently only "http" is supported), local address, and local port.HTTPConnection(URL url) Constructs a connection to the host (port) as given in the url.HTTPConnection(URI uri) Constructs a connection to the host (port) as given in the uri. -
Method Summary
Modifier and TypeMethodDescriptionvoidaddBasicAuthorization(String realm, String user, String passwd) Adds an authorization entry for the "basic" authorization scheme to the list.static booleanaddDefaultModule(Class module, int pos) Adds a module to the default list.voidaddDigestAuthorization(String realm, String user, String passwd) Adds an authorization entry for the "digest" authorization scheme to the list.booleanAdds a module to the current list.Copy resource or colleaction to URL spesified indestinationparameter.Copy resource or colleaction to URL spesified indestinationparameter.Requests that file be DELETEd from the server.Requests that file be DELETEd from the server.static voiddontProxyFor(String host) Add host to the list of hosts which should be accessed directly, not via any proxy set bysetProxyServer().static voiddontProxyFor(String[] hosts) Convenience method to add a number of hosts at once.static booleandoProxyFor(String host) Remove host from the list of hosts for which the proxy should not be used.ExtensionMethod(String method, String file, byte[] data, NVPair[] headers) This is here to allow an arbitrary, non-standard request to be sent.ExtensionMethod(String method, String file, HttpOutputStream os, NVPair[] headers) This is here to allow an arbitrary, non-standard request to be sent.GETs the file.Deprecated.Deprecated.GETs the file with a query consisting of the specified form-data.GETs the file with a query consisting of the specified form-data.booleanreturns whether modules are allowed to prompt or popup dialogs if neccessary.Returns the current context.static booleanGets the default allow-user-action.static ObjectReturns the default context.NVPair[]Gets the current list of default http headers.static Class[]Returns the default list of modules.static intGets the default timeout value to be used for each new HTTPConnection.getHost()Returns the host this connection is talking to.Class[]Returns the list of modules used currently.intgetPort()Returns the port this connection connects to.Returns the protocol this connection is talking.Returns the host of the proxy this connection is using.intReturns the port of the proxy this connection is using.intGets the timeout used for reading response data.Sends the HEAD request.Sends the HEAD request.Sends the HEAD request.Sends the HEAD request.Sends the HEAD request.booleanisCompatibleWith(URI uri) See if the given uri is compatible with this connection.LOCK requestRefresh LOCK request.Create new Collection.Move resource or colleaction to URL spesified indestinationparameter.Move resource or colleaction to URL spesified indestinationparameter.Request OPTIONS from the server.Request OPTIONS from the server.Request OPTIONS from the server.Options(String file, NVPair[] headers, HttpOutputStream stream) Request OPTIONS from the server.POSTs to the specified file.POSTs the raw data to the specified file.POSTs the raw data to the specified file using the specified headers.POSTs the data to the specified file.POSTs the data to the specified file using the specified headers.Post(String file, HttpOutputStream stream) POSTs the data written to the output stream to the specified file.Post(String file, HttpOutputStream stream, NVPair[] headers) POSTs the data written to the output stream to the specified file using the specified headers.POSTs form-data to the specified file.POST's form-data to the specified file using the specified headers.PROPFIND prop request with 'Depth' header specified as 'infinity'.PROPFIND prop request.PropfindAllprop(String resource) PROPFIND allprop request with 'Depth' header specified as 'infinity'.PropfindAllprop(String resource, int depth) PROPFIND allprop request with 'Depth' header specified as 'infinity'.PropfindPropname(String resource) PROPFIND propname request with 'Depth' header specified as 'infinity'.PropfindPropname(String resource, int depth) PROPFIND propname request.PROPPATCH request.PUTs the raw data into the specified file.PUTs the raw data into the specified file using the additional headers.PUTs the data into the specified file.PUTs the data into the specified file using the additional headers for the request.Put(String file, HttpOutputStream stream) PUTs the data written to the output stream into the specified file.Put(String file, HttpOutputStream stream, NVPair[] headers) PUTs the data written to the output stream into the specified file using the additional headers.static booleanremoveDefaultModule(Class module) Removes a module from the default list.booleanremoveModule(Class module) Removes a module from the current list.voidsetAllowUserInteraction(boolean allow) Controls whether modules are allowed to prompt the user or pop up dialogs if neccessary.voidsetContext(Object context) Sets the current context.voidsetCurrentProxy(String host, int port) Sets the proxy used by this instance.static voidsetDefaultAllowUserInteraction(boolean allow) Sets the default allow-user-action.voidsetDefaultHeaders(NVPair[] headers) Sets the default http headers to be sent with each request.static voidsetDefaultTimeout(int time) Sets the default timeout value to be used for each new HTTPConnection.static voidsetProxyServer(String host, int port) Sets the default proxy server to use.voidsetRawMode(boolean raw) Deprecated.This is not really needed anymore; in V0.2 request were synchronous and therefore to do pipelining you needed to disable the processing of responses.static voidsetSocksServer(String host) Sets the SOCKS server to use.static voidsetSocksServer(String host, int port) Sets the SOCKS server to use.static voidsetSocksServer(String host, int port, int version) Sets the SOCKS server to use.voidsetTimeout(int time) Sets the timeout to be used for creating connections and reading responses.protected final HTTPResponsesetupRequest(String method, String resource, NVPair[] headers, byte[] entity, HttpOutputStream stream) Sets up the request, creating the list of headers to send and creating instances of the modules.voidstop()Aborts all the requests currently in progress on this connection and closes all associated sockets.toString()Generates a string of the form protocol://host.domain:port .Requests a TRACE.Requests a TRACE.Refresh LOCK request.
-
Field Details
-
version
The current version of this package.- See Also:
-
HTTP
static final int HTTPpossible http protocols we (might) handle- See Also:
-
HTTPS
static final int HTTPS- See Also:
-
SHTTP
static final int SHTTP- See Also:
-
HTTP_NG
static final int HTTP_NG- See Also:
-
HTTP_1_0
static final int HTTP_1_0some known http versions- See Also:
-
HTTP_1_1
static final int HTTP_1_1- See Also:
-
CD_NONE
static final int CD_NONEContent delimiters- See Also:
-
CD_HDRS
static final int CD_HDRS- See Also:
-
CD_0
static final int CD_0- See Also:
-
CD_CLOSE
static final int CD_CLOSE- See Also:
-
CD_CONTLEN
static final int CD_CONTLEN- See Also:
-
CD_CHUNKED
static final int CD_CHUNKED- See Also:
-
CD_MP_BR
static final int CD_MP_BR- See Also:
-
-
Constructor Details
-
HTTPConnection
Constructs a connection to the host from where the applet was loaded. Note that current security policies only let applets connect home.- Parameters:
applet- the current applet- Throws:
ProtocolNotSuppException
-
HTTPConnection
Constructs a connection to the specified host on port 80- Parameters:
host- the host
-
HTTPConnection
Constructs a connection to the specified host on the specified port- Parameters:
host- the hostport- the port
-
HTTPConnection
Constructs a connection to the specified host on the specified port, using the specified protocol (currently only "http" is supported).- Parameters:
prot- the protocolhost- the hostport- the port, or -1 for the default port- Throws:
ProtocolNotSuppException- if the protocol is not HTTP
-
HTTPConnection
public HTTPConnection(String prot, String host, int port, InetAddress localAddr, int localPort) throws ProtocolNotSuppException Constructs a connection to the specified host on the specified port, using the specified protocol (currently only "http" is supported), local address, and local port.- Parameters:
prot- the protocolhost- the hostport- the port, or -1 for the default portlocalAddr- the local address to bind tolocalPort- the local port to bind to- Throws:
ProtocolNotSuppException- if the protocol is not HTTP
-
HTTPConnection
Constructs a connection to the host (port) as given in the url.- Parameters:
url- the url- Throws:
ProtocolNotSuppException- if the protocol is not HTTP
-
HTTPConnection
Constructs a connection to the host (port) as given in the uri.- Parameters:
uri- the uri- Throws:
ProtocolNotSuppException- if the protocol is not HTTP
-
-
Method Details
-
Head
Sends the HEAD request. This request is just like the corresponding GET except that it only returns the headers and no data.- Parameters:
file- the absolute path of the file- Returns:
- an HTTPResponse structure containing the response
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.- See Also:
-
Head
Sends the HEAD request. This request is just like the corresponding GET except that it only returns the headers and no data.- Parameters:
file- the absolute path of the fileform_data- an array of Name/Value pairs- Returns:
- an HTTPResponse structure containing the response
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.- See Also:
-
Head
public HTTPResponse Head(String file, NVPair[] form_data, NVPair[] headers) throws IOException, ModuleException Sends the HEAD request. This request is just like the corresponding GET except that it only returns the headers and no data.- Parameters:
file- the absolute path of the fileform_data- an array of Name/Value pairsheaders- additional headers- Returns:
- an HTTPResponse structure containing the response
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.- See Also:
-
Head
Sends the HEAD request. This request is just like the corresponding GET except that it only returns the headers and no data.- Parameters:
file- the absolute path of the filequery- the query string; it will be urlencoded- Returns:
- an HTTPResponse structure containing the response
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.- See Also:
-
Head
public HTTPResponse Head(String file, String query, NVPair[] headers) throws IOException, ModuleException Sends the HEAD request. This request is just like the corresponding GET except that it only returns the headers and no data.- Parameters:
file- the absolute path of the filequery- the query string; it will be urlencodedheaders- additional headers- Returns:
- an HTTPResponse structure containing the response
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.- See Also:
-
Get
GETs the file.- Parameters:
file- the absolute path of the file- Returns:
- an HTTPResponse structure containing the response
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.
-
Get
GETs the file with a query consisting of the specified form-data. The data is urlencoded, turned into a string of the form"name1=value1&name2=value2"and then sent as a query string.- Parameters:
file- the absolute path of the fileform_data- an array of Name/Value pairs- Returns:
- an HTTPResponse structure containing the response
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.
-
Get
public HTTPResponse Get(String file, NVPair[] form_data, NVPair[] headers) throws IOException, ModuleException GETs the file with a query consisting of the specified form-data. The data is urlencoded, turned into a string of the form"name1=value1&name2=value2"and then sent as a query string.- Parameters:
file- the absolute path of the fileform_data- an array of Name/Value pairsheaders- additional headers- Returns:
- an HTTPResponse structure containing the response
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.
-
Get
Deprecated.GETs the file using the specified query string. The query string is first urlencoded.- Parameters:
file- the absolute path of the filequery- the query- Returns:
- an HTTPResponse structure containing the response
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.
-
Get
@Deprecated public HTTPResponse Get(String file, String query, NVPair[] headers) throws IOException, ModuleException Deprecated.GETs the file using the specified query string. The query string is first urlencoded.- Parameters:
file- the absolute path of the filequery- the query stringheaders- additional headers- Returns:
- an HTTPResponse structure containing the response
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.
-
Post
POSTs to the specified file. No data is sent.- Parameters:
file- the absolute path of the file- Returns:
- an HTTPResponse structure containing the response
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.
-
Post
POSTs form-data to the specified file. The data is first urlencoded and then turned into a string of the form"name1=value1&name2=value2". A Content-type header with the value application/x-www-form-urlencoded is added.- Parameters:
file- the absolute path of the fileform_data- an array of Name/Value pairs- Returns:
- an HTTPResponse structure containing the response
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.
-
Post
public HTTPResponse Post(String file, NVPair[] form_data, NVPair[] headers) throws IOException, ModuleException POST's form-data to the specified file using the specified headers. The data is first urlencoded and then turned into a string of the form"name1=value1&name2=value2". If no Content-type header is given then one is added with a value of application/x-www-form-urlencoded.- Parameters:
file- the absolute path of the fileform_data- an array of Name/Value pairsheaders- additional headers- Returns:
- a HTTPResponse structure containing the response
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.
-
Post
POSTs the data to the specified file. The data is converted to an array of bytes using the default character converter. The request is sent using the content-type "application/octet-stream".- Parameters:
file- the absolute path of the filedata- the data- Returns:
- an HTTPResponse structure containing the response
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.- See Also:
-
Post
public HTTPResponse Post(String file, String data, NVPair[] headers) throws IOException, ModuleException POSTs the data to the specified file using the specified headers.- Parameters:
file- the absolute path of the filedata- the dataheaders- additional headers- Returns:
- an HTTPResponse structure containing the response
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.- See Also:
-
Post
POSTs the raw data to the specified file. The request is sent using the content-type "application/octet-stream"- Parameters:
file- the absolute path of the filedata- the data- Returns:
- an HTTPResponse structure containing the response
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.
-
Post
public HTTPResponse Post(String file, byte[] data, NVPair[] headers) throws IOException, ModuleException POSTs the raw data to the specified file using the specified headers.- Parameters:
file- the absolute path of the filedata- the dataheaders- additional headers- Returns:
- an HTTPResponse structure containing the response
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.
-
Post
POSTs the data written to the output stream to the specified file. The request is sent using the content-type "application/octet-stream"- Parameters:
file- the absolute path of the filestream- the output stream on which the data is written- Returns:
- an HTTPResponse structure containing the response
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.
-
Post
public HTTPResponse Post(String file, HttpOutputStream stream, NVPair[] headers) throws IOException, ModuleException POSTs the data written to the output stream to the specified file using the specified headers.- Parameters:
file- the absolute path of the filestream- the output stream on which the data is writtenheaders- additional headers- Returns:
- an HTTPResponse structure containing the response
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.
-
Put
PUTs the data into the specified file. The data is converted to an array of bytes using the default character converter. The request ist sent using the content-type "application/octet-stream".- Parameters:
file- the absolute path of the filedata- the data- Returns:
- an HTTPResponse structure containing the response
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.- See Also:
-
Put
public HTTPResponse Put(String file, String data, NVPair[] headers) throws IOException, ModuleException PUTs the data into the specified file using the additional headers for the request.- Parameters:
file- the absolute path of the filedata- the dataheaders- additional headers- Returns:
- an HTTPResponse structure containing the response
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.- See Also:
-
Put
PUTs the raw data into the specified file. The request is sent using the content-type "application/octet-stream".- Parameters:
file- the absolute path of the filedata- the data- Returns:
- an HTTPResponse structure containing the response
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.
-
Put
public HTTPResponse Put(String file, byte[] data, NVPair[] headers) throws IOException, ModuleException PUTs the raw data into the specified file using the additional headers.- Parameters:
file- the absolute path of the filedata- the dataheaders- any additional headers- Returns:
- an HTTPResponse structure containing the response
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.
-
Put
PUTs the data written to the output stream into the specified file. The request is sent using the content-type "application/octet-stream".- Parameters:
file- the absolute path of the filestream- the output stream on which the data is written- Returns:
- an HTTPResponse structure containing the response
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.
-
Put
public HTTPResponse Put(String file, HttpOutputStream stream, NVPair[] headers) throws IOException, ModuleException PUTs the data written to the output stream into the specified file using the additional headers.- Parameters:
file- the absolute path of the filestream- the output stream on which the data is writtenheaders- any additional headers- Returns:
- an HTTPResponse structure containing the response
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.
-
Options
Request OPTIONS from the server. If file is "*" then the request applies to the server as a whole; otherwise it applies only to that resource.- Parameters:
file- the absolute path of the resource, or "*"- Returns:
- an HTTPResponse structure containing the response
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.
-
Options
Request OPTIONS from the server. If file is "*" then the request applies to the server as a whole; otherwise it applies only to that resource.- Parameters:
file- the absolute path of the resource, or "*"headers- the headers containing optional info.- Returns:
- an HTTPResponse structure containing the response
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.
-
Options
public HTTPResponse Options(String file, NVPair[] headers, byte[] data) throws IOException, ModuleException Request OPTIONS from the server. If file is "*" then the request applies to the server as a whole; otherwise it applies only to that resource.- Parameters:
file- the absolute path of the resource, or "*"headers- the headers containing optional info.data- any data to be sent in the optional body- Returns:
- an HTTPResponse structure containing the response
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.
-
Options
public HTTPResponse Options(String file, NVPair[] headers, HttpOutputStream stream) throws IOException, ModuleException Request OPTIONS from the server. If file is "*" then the request applies to the server as a whole; otherwise it applies only to that resource.- Parameters:
file- the absolute path of the resource, or "*"headers- the headers containing optional info.stream- an output stream for sending the optional body- Returns:
- an HTTPResponse structure containing the response
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.
-
Delete
Requests that file be DELETEd from the server.- Parameters:
file- the absolute path of the resource- Returns:
- an HTTPResponse structure containing the response
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.
-
Delete
Requests that file be DELETEd from the server.- Parameters:
file- the absolute path of the resourceheaders- additional headers- Returns:
- an HTTPResponse structure containing the response
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.
-
Trace
Requests a TRACE. Headers of particular interest here are "Via" and "Max-Forwards".- Parameters:
file- the absolute path of the resourceheaders- additional headers- Returns:
- an HTTPResponse structure containing the response
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.
-
Trace
Requests a TRACE.- Parameters:
file- the absolute path of the resource- Returns:
- an HTTPResponse structure containing the response
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.
-
Copy
public HTTPResponse Copy(String source, String destination, boolean override, boolean norecursive) throws IOException, ModuleException Copy resource or colleaction to URL spesified indestinationparameter. If destination resource exist operation will be fail.- Parameters:
source- the source URL.destination- the destination URL.override- must destination resource be overwrite.norecursive- on collection resource it means copy only resource but not child.- Returns:
- an HTTPResponse structure containing the response.
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.
-
Copy
Copy resource or colleaction to URL spesified indestinationparameter. If destination resource exist operation will be fail.- Parameters:
source- the source URL.destination- the destination URL.- Returns:
- an HTTPResponse structure containing the response.
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.
-
Move
public HTTPResponse Move(String source, String destination, boolean override) throws IOException, ModuleException Move resource or colleaction to URL spesified indestinationparameter.- Parameters:
source- the source URL.destination- the destination URL.override- must destination resource be overwrite.- Returns:
- an HTTPResponse structure containing the response.
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.
-
Move
Move resource or colleaction to URL spesified indestinationparameter. If destination resource exist operation will be fail.- Parameters:
source- the source URL.destination- the destination URL.- Returns:
- an HTTPResponse structure containing the response.
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.
-
MkCol
Create new Collection.- Parameters:
resource- the URL for Collection creation.- Returns:
- an HTTPResponse structure containing the response.
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.
-
PropfindAllprop
PROPFIND allprop request with 'Depth' header specified as 'infinity'.- Parameters:
resource- resource's URL.depth- the depth of request, if specified as -1 then 'infinity' will be used.- Returns:
- an HTTPResponse structure containing the response.
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.
-
PropfindAllprop
PROPFIND allprop request with 'Depth' header specified as 'infinity'.- Parameters:
resource- resource's URL.- Returns:
- an HTTPResponse structure containing the response.
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.
-
Propfind
public HTTPResponse Propfind(String resource, List<String> props, int depth) throws IOException, ModuleException PROPFIND prop request.- Parameters:
resource- resource's URL.props- the List<String> of resource's properties.depth- the depth of request, if specified as -1 then 'infinity' will be used.- Returns:
- an HTTPResponse structure containing the response.
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.
-
Propfind
public HTTPResponse Propfind(String resource, List<String> props) throws IOException, ModuleException PROPFIND prop request with 'Depth' header specified as 'infinity'.- Parameters:
resource- resource's URL.props- the List<String> of resource's properties.- Returns:
- an HTTPResponse structure containing the response.
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.
-
PropfindPropname
public HTTPResponse PropfindPropname(String resource, int depth) throws IOException, ModuleException PROPFIND propname request.- Parameters:
resource- resource's URL.depth- the depth of request, if specified as -1 then 'infinity' will be used.- Returns:
- an HTTPResponse structure containing the response.
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.
-
PropfindPropname
PROPFIND propname request with 'Depth' header specified as 'infinity'.- Parameters:
resource- resource's URL.- Returns:
- an HTTPResponse structure containing the response.
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.
-
Proppath
public HTTPResponse Proppath(String resource, Map<String, List<String>> propsSet, List<String> propsRemove) throws IOException, ModuleExceptionPROPPATCH request.- Parameters:
resource- resource's URL.propsSet- properties for set.propsRemove- properties for remove.- Returns:
- an HTTPResponse structure containing the response.
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.
-
Lock
public HTTPResponse Lock(String resource, boolean isExclusive, boolean isRecursive, long timeout) throws IOException, ModuleException LOCK request- Parameters:
resource- resource's URL.isExclusive- if true then exclusive type of lock will be set otherwise shared lock.isRecursive- if true then lock on collection will be recursive otherwise child resource will be not locked.timeout- the timeout for lock, if -1 then 'infinity' will be send.- Returns:
- an HTTPResponse structure containing the response.
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.
-
Lock
public HTTPResponse Lock(String resource, long timeout, String lockToken) throws IOException, ModuleException Refresh LOCK request.- Parameters:
resource- resource's URL.timeout- the timeout for lock, if -1 then 'infinity' will be send.lockToken- the locktoken.- Returns:
- an HTTPResponse structure containing the response.
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.
-
Unlock
Refresh LOCK request.- Parameters:
resource- resource's URL.lockToken- the locktoken.- Returns:
- an HTTPResponse structure containing the response.
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.
-
ExtensionMethod
public HTTPResponse ExtensionMethod(String method, String file, byte[] data, NVPair[] headers) throws IOException, ModuleException This is here to allow an arbitrary, non-standard request to be sent. I'm assuming you know what you are doing...- Parameters:
method- the extension methodfile- the absolute path of the resource, or nulldata- optional data, or nullheaders- optional headers, or null- Returns:
- an HTTPResponse structure containing the response
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.
-
ExtensionMethod
public HTTPResponse ExtensionMethod(String method, String file, HttpOutputStream os, NVPair[] headers) throws IOException, ModuleException This is here to allow an arbitrary, non-standard request to be sent. I'm assuming you know what you are doing...- Parameters:
method- the extension methodfile- the absolute path of the resource, or nullheaders- optional headers, or null- Returns:
- an HTTPResponse structure containing the response
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.
-
stop
public void stop()Aborts all the requests currently in progress on this connection and closes all associated sockets. You usually do not need to invoke this - it only meant for when you need to abruptly stop things, such as for example the stop button in a browser.Note: there is a small window where a request method such as
Get()may have been invoked but the request has not been built and added to the list. Any request in this window will not be aborted.- Since:
- V0.2-3
-
setDefaultHeaders
Sets the default http headers to be sent with each request. The actual headers sent are determined as follows: for each header specified in multiple places a value given as part of the request takes priority over any default values set by this method, which in turn takes priority over any built-in default values. A different way of looking at it is that we start off with a list of all headers specified with the request, then add any default headers set by this method which aren't already in our list, and finally add any built-in headers which aren't yet in the list. There is one exception to this rule: the "Content-length" header is always ignored; and when posting form-data any default "Content-type" is ignored in favor of the built-in "application/x-www-form-urlencoded" (however it will be overriden by any content-type header specified as part of the request).Typical headers you might want to set here are "Accept" and its "Accept-*" relatives, "Connection", "From", "User-Agent", etc.
- Parameters:
headers- an array of header-name/value pairs (do not give the separating ':').
-
getDefaultHeaders
Gets the current list of default http headers.- Returns:
- an array of header/value pairs.
-
getProtocol
Returns the protocol this connection is talking.- Returns:
- a string containing the (lowercased) protocol
-
getHost
Returns the host this connection is talking to.- Returns:
- a string containing the (lowercased) host name.
-
getPort
public int getPort()Returns the port this connection connects to. This is always the actual port number, never -1.- Returns:
- the port number
-
getProxyHost
Returns the host of the proxy this connection is using.- Returns:
- a string containing the (lowercased) host name.
-
getProxyPort
public int getProxyPort()Returns the port of the proxy this connection is using.- Returns:
- the port number
-
isCompatibleWith
See if the given uri is compatible with this connection. Compatible means that the given uri can be retrieved using this connection object.- Parameters:
uri- the URI to check- Returns:
- true if they're compatible, false otherwise
- Since:
- V0.3-2
-
setRawMode
public void setRawMode(boolean raw) Deprecated.This is not really needed anymore; in V0.2 request were synchronous and therefore to do pipelining you needed to disable the processing of responses.Sets/Resets raw mode. In raw mode all modules are bypassed, meaning the automatic handling of authorization requests, redirections, cookies, etc. is turned off.The default is false.
- Parameters:
raw- if true removes all modules (except for the retry module)- See Also:
-
setDefaultTimeout
public static void setDefaultTimeout(int time) Sets the default timeout value to be used for each new HTTPConnection. The default is 0.- Parameters:
time- the timeout in milliseconds.- See Also:
-
getDefaultTimeout
public static int getDefaultTimeout()Gets the default timeout value to be used for each new HTTPConnection.- Returns:
- the timeout in milliseconds.
- See Also:
-
setTimeout
public void setTimeout(int time) Sets the timeout to be used for creating connections and reading responses. When a timeout expires the operation will throw an InterruptedIOException. The operation may be restarted again afterwards. If the operation is not restarted and it is a read operation (i.e HTTPResponse.xxxx()) thenresp.getInputStream().close()should be invoked.When creating new sockets the timeout will limit the time spent doing the host name translation and establishing the connection with the server.
The timeout also influences the reading of the response headers. However, it does not specify a how long, for example, getStatusCode() may take, as might be assumed. Instead it specifies how long a read on the socket may take. If the response dribbles in slowly with packets arriving quicker than the timeout then the method will complete normally. I.e. the exception is only thrown if nothing arrives on the socket for the specified time. Furthermore, the timeout only influences the reading of the headers, not the reading of the body.
Read Timeouts are associated with responses, so that you may change this value before each request and it won't affect the reading of responses to previous requests.
- Parameters:
time- the time in milliseconds. A time of 0 means wait indefinitely.- See Also:
-
getTimeout
public int getTimeout()Gets the timeout used for reading response data.- Returns:
- the current timeout value
- See Also:
-
setAllowUserInteraction
public void setAllowUserInteraction(boolean allow) Controls whether modules are allowed to prompt the user or pop up dialogs if neccessary.- Parameters:
allow- if true allows modules to interact with user.
-
getAllowUserInteraction
public boolean getAllowUserInteraction()returns whether modules are allowed to prompt or popup dialogs if neccessary.- Returns:
- true if modules are allowed to interact with user.
-
setDefaultAllowUserInteraction
public static void setDefaultAllowUserInteraction(boolean allow) Sets the default allow-user-action.- Parameters:
allow- if true allows modules to interact with user.
-
getDefaultAllowUserInteraction
public static boolean getDefaultAllowUserInteraction()Gets the default allow-user-action.- Returns:
- true if modules are allowed to interact with user.
-
getDefaultModules
Returns the default list of modules.- Returns:
- an array of classes
-
addDefaultModule
Adds a module to the default list. It must implement the HTTPClientModule interface. If the module is already in the list then this method does nothing. This method only affects instances of HTTPConnection created after this method has been invoked; it does not affect existing instances.Example:
HTTPConnection.addDefaultModule(Class.forName("HTTPClient.CookieModule"), 1);adds the cookie module as the second module in the list.The default list is created at class initialization time from the property HTTPClient.Modules. This must contain a "|" separated list of classes in the order they're to be invoked. If this property is not set it defaults to: "HTTPClient.RetryModule | HTTPClient.CookieModule | HTTPClient.RedirectionModule | HTTPClient.AuthorizationModule | HTTPClient.DefaultModule | HTTPClient.TransferEncodingModule | HTTPClient.ContentMD5Module | HTTPClient.ContentEncodingModule"
- Parameters:
module- the module's Class objectpos- the position of this module in the list; if pos >= 0 then this is the absolute position in the list (0 is the first position); if pos < 0 then this is the position relative to the end of the list (-1 means the last element, -2 the second to last element, etc).- Returns:
- true if module was successfully added; false if the module is already in the list.
- Throws:
ArrayIndexOutOfBoundsException- if pos > list-size or if pos < -(list-size).ClassCastException- if module does not implement the HTTPClientModule interface.RuntimeException- if module cannot be instantiated.- See Also:
-
removeDefaultModule
Removes a module from the default list. If the module is not in the list it does nothing. This method only affects instances of HTTPConnection created after this method has been invoked; it does not affect existing instances.- Parameters:
module- the module's Class object- Returns:
- true if module was successfully removed; false otherwise
-
getModules
Returns the list of modules used currently.- Returns:
- an array of classes
-
addModule
Adds a module to the current list. It must implement the HTTPClientModule interface. If the module is already in the list then this method does nothing.- Parameters:
module- the module's Class objectpos- the position of this module in the list; if pos >= 0 then this is the absolute position in the list (0 is the first position); if pos < 0 then this is the position relative to the end of the list (-1 means the last element, -2 the second to last element, etc).- Returns:
- true if module was successfully added; false if the module is already in the list.
- Throws:
ArrayIndexOutOfBoundsException- if pos > list-size or if pos < -(list-size).ClassCastException- if module does not implement the HTTPClientModule interface.RuntimeException- if module cannot be instantiated.- See Also:
-
removeModule
Removes a module from the current list. If the module is not in the list it does nothing.- Parameters:
module- the module's Class object- Returns:
- true if module was successfully removed; false otherwise
-
setContext
Sets the current context. The context is used by modules such as the AuthorizationModule and the CookieModule which keep lists of info that is normally shared between all instances of HTTPConnection. This is usually the desired behaviour. However, in some cases one would like to simulate multiple independent clients within the same application and hence the sharing of such info should be restricted. This is where the context comes in. Modules will only share their info between requests using the same context (i.e. they keep multiple lists, one for each context).The context may be any object. Contexts are considered equal if
equals()returns true. Examples of useful context objects are threads (e.g. if you are running multiple clients, one per thread) and sockets (e.g. if you are implementing a gateway).When a new HTTPConnection is created it is initialized with a default context which is the same for all instances. This method must be invoked immediately after a new HTTPConnection is created and before any request method is invoked. Furthermore, this method may only be called once (i.e. the context is "sticky").
- Parameters:
context- the new context; must be non-null- Throws:
IllegalArgumentException- if context is nullIllegalStateException- if the context has already been set
-
getContext
Returns the current context.- Returns:
- the current context, or the default context if
setContext()hasn't been invoked - See Also:
-
getDefaultContext
Returns the default context.- Returns:
- the default context
- See Also:
-
addDigestAuthorization
Adds an authorization entry for the "digest" authorization scheme to the list. If an entry already exists for the "digest" scheme and the specified realm then it is overwritten.This is a convenience method and just invokes the corresponding method in AuthorizationInfo.
- Parameters:
realm- the realmuser- the usernamepasswd- the password- See Also:
-
addBasicAuthorization
Adds an authorization entry for the "basic" authorization scheme to the list. If an entry already exists for the "basic" scheme and the specified realm then it is overwritten.This is a convenience method and just invokes the corresponding method in AuthorizationInfo.
- Parameters:
realm- the realmuser- the usernamepasswd- the password- See Also:
-
setProxyServer
Sets the default proxy server to use. The proxy will only be used for new HTTPConnections created after this call and will not affect currrent instances of HTTPConnection. A null or empty string host parameter disables the proxy.In an application or using the Appletviewer an alternative to this method is to set the following properties (either in the properties file or on the command line): http.proxyHost and http.proxyPort. Whether http.proxyHost is set or not determines whether a proxy server is used.
If the proxy server requires authorization and you wish to set this authorization information in the code, then you may use any of the AuthorizationInfo.addXXXAuthorization() methods to do so. Specify the same host and port as in this method. If you have not given any authorization info and the proxy server requires authorization then you will be prompted for the necessary info via a popup the first time you do a request.
- Parameters:
host- the host on which the proxy server resides.port- the port the proxy server is listening on.- See Also:
-
setCurrentProxy
Sets the proxy used by this instance. This can be used to override the proxy setting inherited from the default proxy setting. A null or empty string host parameter disables the proxy.Note that if you set a proxy for the connection using this method, and a request made over this connection is redirected to a different server, then the connection used for new server will not pick this proxy setting, but instead will use the default proxy settings.
- Parameters:
host- the host the proxy runs onport- the port the proxy is listening on- See Also:
-
dontProxyFor
Add host to the list of hosts which should be accessed directly, not via any proxy set bysetProxyServer().The host may be any of:
- a complete host name (e.g. "www.disney.com")
- a domain name; domain names must begin with a dot (e.g. ".disney.com")
- an IP-address (e.g. "12.34.56.78")
- an IP-subnet, specified as an IP-address and a netmask separated by a "/" (e.g. "34.56.78/255.255.255.192"); a 0 bit in the netmask means that that bit won't be used in the comparison (i.e. the addresses are AND'ed with the netmask before comparison).
The two properties HTTPClient.nonProxyHosts and http.nonProxyHosts are used when this class is loaded to initialize the list of non-proxy hosts. The second property is only read if the first one is not set; the second property is also used the JDK's URLConnection. These properties must contain a "|" separated list of entries which conform to the above rules for the host parameter (e.g. "11.22.33.44|.disney.com").
- Parameters:
host- a host name, domain name, IP-address or IP-subnet.- Throws:
ParseException- if the length of the netmask does not match the length of the IP-address
-
dontProxyFor
Convenience method to add a number of hosts at once. If any one host is null or cannot be parsed it is ignored.- Parameters:
hosts- The list of hosts to set- Since:
- V0.3-2
- See Also:
-
doProxyFor
Remove host from the list of hosts for which the proxy should not be used. This modifies the same list thatdontProxyFor()uses, i.e. this is used to undo adontProxyFor()setting. The syntax for host is specified indontProxyFor().- Parameters:
host- a host name, domain name, IP-address or IP-subnet.- Returns:
- true if the remove was sucessful, false otherwise
- Throws:
ParseException- if the length of the netmask does not match the length of the IP-address- See Also:
-
setSocksServer
Sets the SOCKS server to use. The server will only be used for new HTTPConnections created after this call and will not affect currrent instances of HTTPConnection. A null or empty string host parameter disables SOCKS.The code will try to determine the SOCKS version to use at connection time. This might fail for a number of reasons, however, in which case you must specify the version explicitly.
- Parameters:
host- the host on which the proxy server resides. The port used is the default port 1080.- See Also:
-
setSocksServer
Sets the SOCKS server to use. The server will only be used for new HTTPConnections created after this call and will not affect currrent instances of HTTPConnection. A null or empty string host parameter disables SOCKS.The code will try to determine the SOCKS version to use at connection time. This might fail for a number of reasons, however, in which case you must specify the version explicitly.
- Parameters:
host- the host on which the proxy server resides.port- the port the proxy server is listening on.- See Also:
-
setSocksServer
Sets the SOCKS server to use. The server will only be used for new HTTPConnections created after this call and will not affect currrent instances of HTTPConnection. A null or empty string host parameter disables SOCKS.In an application or using the Appletviewer an alternative to this method is to set the following properties (either in the properties file or on the command line): HTTPClient.socksHost, HTTPClient.socksPort and HTTPClient.socksVersion. Whether HTTPClient.socksHost is set or not determines whether a SOCKS server is used; if HTTPClient.socksPort is not set it defaults to 1080; if HTTPClient.socksVersion is not set an attempt will be made to automatically determine the version used by the server.
Note: If you have also set a proxy server then a connection will be made to the SOCKS server, which in turn then makes a connection to the proxy server (possibly via other SOCKS servers), which in turn makes the final connection.
If the proxy server is running SOCKS version 5 and requires username/password authorization, and you wish to set this authorization information in the code, then you may use the AuthorizationInfo.addAuthorization() method to do so. Specify the same host and port as in this method, give the scheme "SOCKS5" and the realm "USER/PASS", set the cookie to null and the params to an array containing a single NVPair in turn containing the username and password. Example:
NVPair[] up = { new NVPair(username, password) }; AuthorizationInfo.addAuthorization(host, port, "SOCKS5", "USER/PASS", null, up);If you have not given any authorization info and the proxy server requires authorization then you will be prompted for the necessary info via a popup the first time you do a request.- Parameters:
host- the host on which the proxy server resides.port- the port the proxy server is listening on.version- the SOCKS version the server is running. Currently this must be '4' or '5'.- Throws:
SocksException- If version is not '4' or '5'.
-
setupRequest
protected final HTTPResponse setupRequest(String method, String resource, NVPair[] headers, byte[] entity, HttpOutputStream stream) throws IOException, ModuleException Sets up the request, creating the list of headers to send and creating instances of the modules. This may be invoked by subclasses which add further methods (such as those from DAV and IPP).- Parameters:
method- GET, POST, etc.resource- the resourceheaders- an array of headers to be usedentity- the entity (or null)stream- the output stream (or null) - only one of stream and entity may be non-null- Returns:
- the response.
- Throws:
IOException- when an exception is returned from the socket.ModuleException- if an exception is encountered in any module.
-
toString
Generates a string of the form protocol://host.domain:port .
-