Class HTTPMethod
- java.lang.Object
-
- ucar.httpservices.HTTPMethod
-
- All Implemented Interfaces:
Closeable,AutoCloseable,Comparable<HTTPMethod>
@NotThreadSafe public class HTTPMethod extends Object implements Closeable, Comparable<HTTPMethod>
HTTPMethod is the encapsulation of specific kind of server request: GET, HEAD, POST, etc. The general processing sequence is as follows.- Create an HTTPMethod object using one of the
methods of HTTPFactory (e.g. HTTPFactory.Get()).
- Set parameters and headers of the returned HTTPMethod instance.
- Invoke the execute() method to actually make
the request.
- Extract response headers.
- Extract any body of the response in one of several forms:
an Inputstream, a byte array, or a String.
- Close the method.
The arguments to the factory method are as follows.
- An HTTPSession instance (optional).
- A URL.
Method URLs may be specified in any of three ways.
- It may be inherited from the URL specified when
the session was created.
- It may be specified as part of the HTTPMethod constructor (via the factory). If none is specified, then the session URL is used.
Legal url arguments to HTTPMethod are constrained by the URL specified in creating the HTTPSession instance. If the session was constructed with a specified URL, then any url specified to HTTMethod (via the factory) must be "compatible" with the session URL. The term "compatible" basically means that the session url's host+port is the same as that of the specified method url. This maintains the semantics of the Session but allows flexibility in accessing data from the server.
One-Shot Operation: A reasonably common use case is when a client wants to create a method, execute it, get the response, and close the method. For this use case, creating a session and making sure it gets closed can be a tedious proposition. To support this use case, HTTPMethod supports what amounts to a one-shot use. The steps are as follows:
- HTTPMethod method = HTTPFactory.Get(
); note that this implicitly creates a session internal to the method instance. - Set any session parameters or headers using method.getSession().setXXX
- Set any parameters and headers on method
- method.execute();
- Get any response method headers
- InputStream stream = method.getResponseBodyAsStream()
- process the stream
- stream.close()
- Set any session parameters or headers using method.getSession().setXXX
- Closing the method (directly or through stream.close()) will close the one-shot session created by the method.
- Closing the stream will close the underlying method, so it is not necessary to call method.close(). However, if you, for example, get the response body using getResponseBodyAsString(), then you need to explicitly call method.close(). The reason is that the stream is likely to be passed out of the scope in which the method was created, hence method.close() is not easily accessible. In the second case, however, this will occur in the same scope as the method and so method.close() is accessible.
For testing purposes, and to allow use of Spring Servlet Mocking, it is possible to set a special execution action (see executeRaw).
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static interfaceHTTPMethod.Executor
-
Field Summary
Fields Modifier and Type Field Description protected booleanclosedprotected org.apache.http.HttpEntitycontentprotected org.apache.http.client.config.RequestConfigdebugconfigprotected booleanexecutedprotected Map<String,String>headersprotected org.apache.http.client.methods.HttpRequestBaselastrequestprotected org.apache.http.HttpResponselastresponseprotected booleanlocalsessionprotected HTTPSession.Methodsmethodkindprotected HTTPMethodStreammethodstreamprotected URImethodurlstatic HTTPMethod.ExecutorMOCKEXECUTORprotected long[]rangeprotected HTTPSessionsessionprotected Map<ucar.httpservices.HTTPSession.Prop,Object>settingsstatic booleanTESTINGprotected Stringuserinfo
-
Constructor Summary
Constructors Modifier Constructor Description protectedHTTPMethod()
-
Method Summary
All Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description protected org.apache.http.client.methods.HttpRequestBasebuildRequest(org.apache.http.client.methods.RequestBuilder rb, Map<ucar.httpservices.HTTPSession.Prop,Object> settings)protected org.apache.http.client.config.RequestConfigbuildRequestConfig(Map<ucar.httpservices.HTTPSession.Prop,Object> settings)booleancanHoldContent()voidclose()Calling close will force the method to close, and will force any open stream to terminate.intcompareTo(HTTPMethod o)protected voidconfigClient(org.apache.http.impl.client.HttpClientBuilder cb, Map<ucar.httpservices.HTTPSession.Prop,Object> settings)org.apache.http.client.methods.HttpRequestBasedebugRequest()org.apache.http.HttpResponsedebugResponse()intexecute()Create a request, add headers, and content, then send to HTTPSession to do the bulk of the work.org.apache.http.HttpResponseexecuteRaw()Create a request, add headers, and content, then send to HTTPSession to do the bulk of the work.StringgetCharSet()org.apache.http.client.config.RequestConfiggetDebugConfig()StringgetMethodKind()StringgetName()Deprecated.StringgetPath()protected org.apache.http.client.methods.RequestBuildergetRequestBuilder()com.google.common.collect.Multimap<String,String>getRequestHeaders()Get all Request headers as a map of name to list of values.Optional<String>getRequestHeaderValue(String name)com.google.common.collect.ImmutableSortedMap<String,com.google.common.collect.ImmutableList<HttpNameValue>>getRequestHeaderValues()StringgetRequestLine()byte[]getResponseAsBytes()byte[]getResponseAsBytes(int maxbytes)InputStreamgetResponseAsStream()StringgetResponseAsString()StringgetResponseAsString(String charset)InputStreamgetResponseBodyAsStream()StringgetResponseCharSet()com.google.common.collect.Multimap<String,String>getResponseHeaders()Get all Response headers as a map of name to list of values.Optional<String>getResponseHeaderValue(String name)com.google.common.collect.ImmutableSortedMap<String,com.google.common.collect.ImmutableList<HttpNameValue>>getResponseHeaderValues()HTTPSessiongetSession()intgetStatusCode()StringgetStatusLine()StringgetStatusText()URIgetURI()booleanhasStreamOpen()booleanisClosed()booleanisSessionLocal()protected booleansessionCompatible(URI otheruri)protected booleansessionCompatible(org.apache.http.auth.AuthScope other)Test that the given url is "compatible" with the session specified dataset.protected booleansessionCompatible(org.apache.http.HttpHost otherhost)Deprecated.HTTPMethodsetCompression(String compressors)protected voidsetcontent(org.apache.http.client.methods.RequestBuilder rb)HTTPMethodsetFollowRedirects(boolean tf)protected voidsetheaders(org.apache.http.client.methods.RequestBuilder rb, Map<String,String> headers)HTTPMethodsetMaxRedirects(int n)HTTPMethodsetMethodHeaders(List<org.apache.http.Header> headers)Deprecated.HTTPMethodsetRange(long lo, long hi)HTTPMethodsetRequestContent(org.apache.http.HttpEntity content)HTTPMethodsetRequestHeader(String name, String value)Deprecated.protected HTTPMethodsetRequestHeader(org.apache.http.Header h)Deprecated.HTTPMethodsetSOTimeout(int n)HTTPMethodsetUserAgent(String agent)HTTPMethodsetUseSessions(boolean tf)
-
-
-
Field Detail
-
TESTING
public static boolean TESTING
-
MOCKEXECUTOR
public static HTTPMethod.Executor MOCKEXECUTOR
-
session
protected HTTPSession session
-
localsession
protected boolean localsession
-
methodurl
protected URI methodurl
-
userinfo
protected String userinfo
-
content
protected org.apache.http.HttpEntity content
-
methodkind
protected HTTPSession.Methods methodkind
-
methodstream
protected HTTPMethodStream methodstream
-
lastrequest
protected org.apache.http.client.methods.HttpRequestBase lastrequest
-
lastresponse
protected org.apache.http.HttpResponse lastresponse
-
range
protected long[] range
-
closed
protected boolean closed
-
executed
protected boolean executed
-
debugconfig
protected org.apache.http.client.config.RequestConfig debugconfig
-
-
Constructor Detail
-
HTTPMethod
protected HTTPMethod() throws HTTPException- Throws:
HTTPException
-
-
Method Detail
-
compareTo
public int compareTo(HTTPMethod o)
- Specified by:
compareToin interfaceComparable<HTTPMethod>
-
setcontent
protected void setcontent(org.apache.http.client.methods.RequestBuilder rb)
-
close
public void close()
Calling close will force the method to close, and will force any open stream to terminate. If the session is local, Then that too will be closed.- Specified by:
closein interfaceAutoCloseable- Specified by:
closein interfaceCloseable
-
execute
public int execute() throws HTTPExceptionCreate a request, add headers, and content, then send to HTTPSession to do the bulk of the work.- Returns:
- statuscode
- Throws:
HTTPException
-
executeRaw
public org.apache.http.HttpResponse executeRaw() throws HTTPExceptionCreate a request, add headers, and content, then send to HTTPSession to do the bulk of the work.- Returns:
- statuscode
- Throws:
HTTPException
-
buildRequestConfig
protected org.apache.http.client.config.RequestConfig buildRequestConfig(Map<ucar.httpservices.HTTPSession.Prop,Object> settings) throws HTTPException
- Throws:
HTTPException
-
configClient
protected void configClient(org.apache.http.impl.client.HttpClientBuilder cb, Map<ucar.httpservices.HTTPSession.Prop,Object> settings) throws HTTPException- Throws:
HTTPException
-
setheaders
protected void setheaders(org.apache.http.client.methods.RequestBuilder rb, Map<String,String> headers)
-
getRequestBuilder
protected org.apache.http.client.methods.RequestBuilder getRequestBuilder() throws HTTPException- Throws:
HTTPException
-
buildRequest
protected org.apache.http.client.methods.HttpRequestBase buildRequest(org.apache.http.client.methods.RequestBuilder rb, Map<ucar.httpservices.HTTPSession.Prop,Object> settings) throws HTTPException- Throws:
HTTPException
-
getMethodKind
public String getMethodKind()
-
getStatusCode
public int getStatusCode()
-
getStatusLine
public String getStatusLine()
-
getRequestLine
public String getRequestLine()
-
getPath
public String getPath()
-
canHoldContent
public boolean canHoldContent()
-
getResponseBodyAsStream
public InputStream getResponseBodyAsStream()
-
getResponseAsStream
public InputStream getResponseAsStream()
-
getResponseAsBytes
public byte[] getResponseAsBytes(int maxbytes)
-
getResponseAsBytes
public byte[] getResponseAsBytes()
-
getResponseAsString
public String getResponseAsString()
-
getRequestHeaders
public com.google.common.collect.Multimap<String,String> getRequestHeaders()
Get all Request headers as a map of name to list of values. A value may be null.- Returns:
- Map, may be empty but not null.
-
getResponseHeaders
public com.google.common.collect.Multimap<String,String> getResponseHeaders()
Get all Response headers as a map of name to list of values. A value may be null.- Returns:
- Map, may be empty but not null.
-
getRequestHeaderValues
public com.google.common.collect.ImmutableSortedMap<String,com.google.common.collect.ImmutableList<HttpNameValue>> getRequestHeaderValues()
-
getResponseHeaderValues
public com.google.common.collect.ImmutableSortedMap<String,com.google.common.collect.ImmutableList<HttpNameValue>> getResponseHeaderValues()
-
setRequestContent
public HTTPMethod setRequestContent(org.apache.http.HttpEntity content)
-
getCharSet
public String getCharSet()
-
getURI
public URI getURI()
-
getStatusText
public String getStatusText()
-
getResponseCharSet
public String getResponseCharSet()
-
getSession
public HTTPSession getSession()
-
isSessionLocal
public boolean isSessionLocal()
-
hasStreamOpen
public boolean hasStreamOpen()
-
isClosed
public boolean isClosed()
-
setRange
public HTTPMethod setRange(long lo, long hi)
-
setCompression
public HTTPMethod setCompression(String compressors)
-
setFollowRedirects
public HTTPMethod setFollowRedirects(boolean tf)
-
setMaxRedirects
public HTTPMethod setMaxRedirects(int n)
-
setSOTimeout
public HTTPMethod setSOTimeout(int n)
-
setUserAgent
public HTTPMethod setUserAgent(String agent)
-
setUseSessions
public HTTPMethod setUseSessions(boolean tf)
-
sessionCompatible
protected boolean sessionCompatible(org.apache.http.auth.AuthScope other)
Test that the given url is "compatible" with the session specified dataset. Wrapper around HTTPAuthUtil.httphostCompatible().- Parameters:
other- to test for compatibility against this method's- Returns:
- true if compatible, false otherwise.
-
sessionCompatible
protected boolean sessionCompatible(URI otheruri)
-
sessionCompatible
@Deprecated protected boolean sessionCompatible(org.apache.http.HttpHost otherhost)
Deprecated.
-
getDebugConfig
public org.apache.http.client.config.RequestConfig getDebugConfig()
-
debugRequest
public org.apache.http.client.methods.HttpRequestBase debugRequest()
-
debugResponse
public org.apache.http.HttpResponse debugResponse()
-
getName
@Deprecated public String getName()
Deprecated.Deprecated: use getMethodKind- Returns:
- Name of the method: e.g. GET, HEAD, ...
-
setMethodHeaders
@Deprecated public HTTPMethod setMethodHeaders(List<org.apache.http.Header> headers) throws HTTPException
Deprecated.- Throws:
HTTPException
-
setRequestHeader
@Deprecated public HTTPMethod setRequestHeader(String name, String value) throws HTTPException
Deprecated.- Throws:
HTTPException
-
setRequestHeader
@Deprecated protected HTTPMethod setRequestHeader(org.apache.http.Header h) throws HTTPException
Deprecated.- Throws:
HTTPException
-
-