Subversion Repositories javautils

Compare Revisions

No changes between revisions

Regard whitespace Rev 5 → Rev 6

/ViaThinkSoft Java Utils/.classpath
3,14 → 3,14
<classpathentry kind="src" path="src"/>
<classpathentry kind="src" path="test"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
<classpathentry kind="lib" path="C:/eclipse/httpcomponents-client-4.0.1/lib/apache-mime4j-0.6.jar"/>
<classpathentry kind="lib" path="C:/eclipse/httpcomponents-client-4.0.1/lib/commons-codec-1.3.jar"/>
<classpathentry kind="lib" path="C:/eclipse/httpcomponents-client-4.0.1/lib/commons-logging-1.1.1.jar"/>
<classpathentry kind="lib" path="C:/eclipse/httpcomponents-client-4.0.1/lib/httpclient-4.0.1.jar"/>
<classpathentry kind="lib" path="C:/eclipse/httpcomponents-client-4.0.1/lib/httpcore-4.0.1.jar"/>
<classpathentry kind="lib" path="C:/eclipse/httpcomponents-client-4.0.1/lib/httpmime-4.0.1.jar"/>
<classpathentry kind="con" path="org.eclipse.jdt.junit.JUNIT_CONTAINER/4"/>
<classpathentry kind="lib" path="/QSetWebApp/data/TomcatLib/activation.jar"/>
<classpathentry kind="lib" path="/QSetWebApp/data/TomcatLib/mail.jar"/>
<classpathentry kind="lib" path="lib/httpcomponents-client-4.0.1/lib/apache-mime4j-0.6.jar"/>
<classpathentry kind="lib" path="lib/httpcomponents-client-4.0.1/lib/commons-codec-1.3.jar"/>
<classpathentry kind="lib" path="lib/httpcomponents-client-4.0.1/lib/commons-logging-1.1.1.jar"/>
<classpathentry kind="lib" path="lib/httpcomponents-client-4.0.1/lib/httpclient-4.0.1.jar"/>
<classpathentry kind="lib" path="lib/httpcomponents-client-4.0.1/lib/httpcore-4.0.1.jar"/>
<classpathentry kind="lib" path="lib/httpcomponents-client-4.0.1/lib/httpmime-4.0.1.jar"/>
<classpathentry kind="lib" path="lib/javamail/activation.jar"/>
<classpathentry kind="lib" path="lib/javamail/mail.jar"/>
<classpathentry kind="output" path="bin"/>
</classpath>
/ViaThinkSoft Java Utils/lib/httpcomponents-client-4.0.1/NOTICE.txt
0,0 → 1,8
Apache HttpComponents Client
Copyright 1999-2009 The Apache Software Foundation
 
This product includes software developed by
The Apache Software Foundation (http://www.apache.org/).
 
This project contains annotations derived from JCIP-ANNOTATIONS
Copyright (c) 2005 Brian Goetz and Tim Peierls. See http://www.jcip.net
/ViaThinkSoft Java Utils/lib/httpcomponents-client-4.0.1/LICENSE.txt
0,0 → 1,182
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
 
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
 
1. Definitions.
 
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
 
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
 
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
 
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
 
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
 
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
 
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
 
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
 
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
 
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
 
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
 
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
 
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
 
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
 
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
 
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
 
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
 
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
 
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
 
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
 
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
 
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
 
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
 
END OF TERMS AND CONDITIONS
This project contains annotations derived from JCIP-ANNOTATIONS
Copyright (c) 2005 Brian Goetz and Tim Peierls.
See http://www.jcip.net and the Creative Commons Attribution License
(http://creativecommons.org/licenses/by/2.5)
 
/ViaThinkSoft Java Utils/lib/httpcomponents-client-4.0.1/tutorial/html/httpagent.html
0,0 → 1,174
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Chapter&nbsp;5.&nbsp;HTTP client service</title><link rel="stylesheet" href="css/hc-tutorial.css" type="text/css"><meta name="generator" content="DocBook XSL-NS Stylesheets V1.73.2"><link rel="start" href="index.html" title="HttpClient Tutorial"><link rel="up" href="index.html" title="HttpClient Tutorial"><link rel="prev" href="authentication.html" title="Chapter&nbsp;4.&nbsp;HTTP authentication"><link rel="next" href="advanced.html" title="Chapter&nbsp;6.&nbsp;Advanced topics"></head><body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"><div xmlns:fo="http://www.w3.org/1999/XSL/Format" class="banner"><a class="bannerLeft" href="http://www.apache.org/" title="Apache Software Foundation"><img style="border:none;" src="images/asf_logo_wide.gif"></a><a class="bannerRight" href="http://hc.apache.org/httpcomponents-core/" title="Apache HttpComponents Core"><img style="border:none;" src="images/hc_logo.png"></a><div class="clear"></div></div><div class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="3" align="center">Chapter&nbsp;5.&nbsp;HTTP client service</th></tr><tr><td width="20%" align="left"><a accesskey="p" href="authentication.html">Prev</a>&nbsp;</td><th width="60%" align="center">&nbsp;</th><td width="20%" align="right">&nbsp;<a accesskey="n" href="advanced.html">Next</a></td></tr></table><hr></div><div class="chapter" lang="en"><div class="titlepage"><div><div><h2 class="title"><a name="httpagent"></a>Chapter&nbsp;5.&nbsp;HTTP client service</h2></div></div></div>
<div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="d4e984"></a>5.1.&nbsp;HttpClient facade</h2></div></div></div>
<p><code class="interfacename">HttpClient</code> interface represents the most essential
contract for HTTP request execution. It imposes no restrictions or particular details on
the request execution process and leaves the specifics of connection management, state
management, authentication and redirect handling up to individual implementations. This
should make it easier to decorate the interface with additional functionality such as
response content caching.</p>
<p><code class="classname">DefaultHttpClient</code> is the default implementation of the
<code class="interfacename">HttpClient</code> interface. This class acts as a facade to
a number of special purpose handler or strategy interface implementations responsible
for handling of a particular aspect of the HTTP protocol such as redirect or
authentication handling or making decision about connection persistence and keep alive
duration. This enables the users to selectively replace default implementation of those
aspects with custom, application specific ones.</p>
<pre class="programlisting">
DefaultHttpClient httpclient = new DefaultHttpClient();
 
httpclient.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy() {
 
@Override
public long getKeepAliveDuration(
HttpResponse response,
HttpContext context) {
long keepAlive = super.getKeepAliveDuration(response, context);
if (keepAlive == -1) {
// Keep connections alive 5 seconds if a keep-alive value
// has not be explicitly set by the server
keepAlive = 5000;
}
return keepAlive;
}
});
</pre>
<p><code class="classname">DefaultHttpClient</code> also maintains a list of protocol
interceptors intended for processing outgoing requests and incoming responses and
provides methods for managing those interceptors. New protocol interceptors can be
introduced to the protocol processor chain or removed from it if needed. Internally
protocol interceptors are stored in a simple <code class="classname">java.util.ArrayList</code>.
They are executed in the same natural order as they are added to the list.</p>
<pre class="programlisting">
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.removeRequestInterceptorByClass(RequestUserAgent.class);
httpclient.addRequestInterceptor(new HttpRequestInterceptor() {
 
public void process(
HttpRequest request, HttpContext context)
throws HttpException, IOException {
request.setHeader(HTTP.USER_AGENT, "My-own-client");
}
});
</pre>
<p><code class="classname">DefaultHttpClient</code> is thread safe. It is recommended that the
same instance of this class is reused for multiple request executions. When an instance
of <code class="classname">DefaultHttpClient</code> is no longer needed and is about to go out
of scope the connection manager associated with it must be shut down by calling the
<code class="methodname">ClientConnectionManager#shutdown()</code> method.</p>
<pre class="programlisting">
HttpClient httpclient = new DefaultHttpClient();
// Do something useful
httpclient.getConnectionManager().shutdown();
</pre>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="d4e1001"></a>5.2.&nbsp;HttpClient parameters</h2></div></div></div>
<p>These are parameters that be used to customize the behaviour of the default HttpClient
implementation:</p>
<div class="itemizedlist"><ul type="disc"><li>
<p>
<b>'http.protocol.handle-redirects':&nbsp;</b>
defines whether redirects should be handled automatically. This parameter
expects a value of type <code class="classname">java.lang.Boolean</code>. If this
parameter is not HttpClient will handle redirects automatically.
</p>
</li><li>
<p>
<b>'http.protocol.reject-relative-redirect':&nbsp;</b>
defines whether relative redirects should be rejected. HTTP specification
requires the location value be an absolute URI. This parameter expects a
value of type <code class="classname">java.lang.Boolean</code>. If this parameter is
not set relative redirects will be allowed.
</p>
</li><li>
<p>
<b>'http.protocol.max-redirects':&nbsp;</b>
defines the maximum number of redirects to be followed. The limit on
number of redirects is intended to prevent infinite loops caused by broken
server side scripts. This parameter expects a value of type
<code class="classname">java.lang.Integer</code>. If this parameter is not set
no more than 100 redirects will be allowed.
</p>
</li><li>
<p>
<b>'http.protocol.allow-circular-redirects':&nbsp;</b>
defines whether circular redirects (redirects to the same location) should
be allowed. The HTTP spec is not sufficiently clear whether circular
redirects are permitted, therefore optionally they can be enabled. This
parameter expects a value of type <code class="classname">java.lang.Boolean</code>.
If this parameter is not set circular redirects will be disallowed.
</p>
</li><li>
<p>
<b>'http.connection-manager.factory-class-name':&nbsp;</b>
defines the class name of the default
<code class="interfacename">ClientConnectionManager</code> implementation.
This parameter expects a value of type
<code class="classname">java.lang.String</code>. If this parameter is not set
<code class="classname">SingleClientConnManager</code> will be used per
default.
</p>
</li><li>
<p>
<b>'http.virtual-host':&nbsp;</b>
defines the virtual host name to be used in the <code class="literal">Host</code>
header instead of the physical host name. This parameter expects a value of
type <code class="classname">HttpHost</code>. If this parameter is not set name or
IP address of the target host will be used.
</p>
</li><li>
<p>
<b>'http.default-headers':&nbsp;</b>
defines the request headers to be sent per default with each request. This
parameter expects a value of type
<code class="interfacename">java.util.Collection</code> containing
<code class="interfacename">Header</code> objects.
</p>
</li><li>
<p>
<b>'http.default-host':&nbsp;</b>
defines the default host. The default value will be used if the target
host is not explicitly specified in the request URI (relative URIs). This
parameter expects a value of type <code class="classname">HttpHost</code>.
</p>
</li></ul></div>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="d4e1049"></a>5.3.&nbsp;Automcatic redirect handling</h2></div></div></div>
<p>HttpClient handles all types of redirects automatically, except those explicitly
prohibited by the HTTP specification as requiring user intervention. <code class="literal">See
Other</code> (status code 303) redirects on <code class="literal">POST</code> and
<code class="literal">PUT</code> requests are converted to <code class="literal">GET</code> requests as
required by the HTTP specification.</p>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="d4e1056"></a>5.4.&nbsp;HTTP client and execution context</h2></div></div></div>
<p>The <code class="classname">DefaultHttpClient</code> treats HTTP requests as immutable objects
that are never supposed to change in the course of request execution. Instead, it
creates a private mutable copy of the original request object, whose properties can be
updated depending on the execution context. Therefore the final request properties such
as the target host and request URI can be determined by examining the content of the
local HTTP context after the request has been executed.</p>
<pre class="programlisting">
DefaultHttpClient httpclient = new DefaultHttpClient();
 
HttpContext localContext = new BasicHttpContext();
HttpGet httpget = new HttpGet("http://localhost:8080/");
HttpResponse response = httpclient.execute(httpget, localContext);
HttpHost target = (HttpHost) localContext.getAttribute(
ExecutionContext.HTTP_TARGET_HOST);
HttpUriRequest req = (HttpUriRequest) localContext.getAttribute(
ExecutionContext.HTTP_REQUEST);
 
System.out.println("Target host: " + target);
System.out.println("Final request URI: " + req.getURI());
System.out.println("Final request method: " + req.getMethod());
</pre>
</div>
</div><div class="navfooter"><hr><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="authentication.html">Prev</a>&nbsp;</td><td width="20%" align="center">&nbsp;</td><td width="40%" align="right">&nbsp;<a accesskey="n" href="advanced.html">Next</a></td></tr><tr><td width="40%" align="left" valign="top">Chapter&nbsp;4.&nbsp;HTTP authentication&nbsp;</td><td width="20%" align="center"><a accesskey="h" href="index.html">Home</a></td><td width="40%" align="right" valign="top">&nbsp;Chapter&nbsp;6.&nbsp;Advanced topics</td></tr></table></div></body></html>
/ViaThinkSoft Java Utils/lib/httpcomponents-client-4.0.1/tutorial/html/authentication.html
0,0 → 1,357
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Chapter&nbsp;4.&nbsp;HTTP authentication</title><link rel="stylesheet" href="css/hc-tutorial.css" type="text/css"><meta name="generator" content="DocBook XSL-NS Stylesheets V1.73.2"><link rel="start" href="index.html" title="HttpClient Tutorial"><link rel="up" href="index.html" title="HttpClient Tutorial"><link rel="prev" href="statemgmt.html" title="Chapter&nbsp;3.&nbsp;HTTP state management"><link rel="next" href="httpagent.html" title="Chapter&nbsp;5.&nbsp;HTTP client service"></head><body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"><div xmlns:fo="http://www.w3.org/1999/XSL/Format" class="banner"><a class="bannerLeft" href="http://www.apache.org/" title="Apache Software Foundation"><img style="border:none;" src="images/asf_logo_wide.gif"></a><a class="bannerRight" href="http://hc.apache.org/httpcomponents-core/" title="Apache HttpComponents Core"><img style="border:none;" src="images/hc_logo.png"></a><div class="clear"></div></div><div class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="3" align="center">Chapter&nbsp;4.&nbsp;HTTP authentication</th></tr><tr><td width="20%" align="left"><a accesskey="p" href="statemgmt.html">Prev</a>&nbsp;</td><th width="60%" align="center">&nbsp;</th><td width="20%" align="right">&nbsp;<a accesskey="n" href="httpagent.html">Next</a></td></tr></table><hr></div><div class="chapter" lang="en"><div class="titlepage"><div><div><h2 class="title"><a name="authentication"></a>Chapter&nbsp;4.&nbsp;HTTP authentication</h2></div></div></div>
<p>HttpClient provides full support for authentication schemes defined by the HTTP standard
specification. HttpClient's authentication framework can also be extended to support
non-standard authentication schemes such as <code class="literal">NTLM</code> and
<code class="literal">SPNEGO</code>.</p>
<div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="d4e829"></a>4.1.&nbsp;User credentials</h2></div></div></div>
<p>Any process of user authentication requires a set of credentials that can be used to
establish user identity. In the simplest form user crednetials can be just a user name /
password pair. <code class="classname">UsernamePasswordCredentials</code> represents a set of
credentials consisting of a security principal and a password in clear text. This
implementation is sufficient for standard authentication schemes defined by the HTTP
standard specification.</p>
<pre class="programlisting">
UsernamePasswordCredentials creds = new UsernamePasswordCredentials("user", "pwd");
System.out.println(creds.getUserPrincipal().getName());
System.out.println(creds.getPassword());
</pre>
<p>stdout &gt;</p>
<pre class="programlisting">
user
pwd
</pre>
<p><code class="classname">NTCredentials</code> is a Microsoft Windows specific implementation
that includes in addition to the user name / password pair a set of additional Windows
specific attributes such as a name of the user domain, as in Microsoft Windows network
the same user can belong to multiple domains with a different set of
authorizations.</p>
<pre class="programlisting">
NTCredentials creds = new NTCredentials("user", "pwd", "workstation", "domain");
System.out.println(creds.getUserPrincipal().getName());
System.out.println(creds.getPassword());
</pre>
<p>stdout &gt;</p>
<pre class="programlisting">
DOMAIN/user
pwd
</pre>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="d4e841"></a>4.2.&nbsp;Authentication schemes</h2></div></div></div>
<p>The <code class="interfacename">AuthScheme</code> interface represents an abstract
challenge-response oriented authentication scheme. An authentication scheme is expected
to support the following functions:</p>
<div class="itemizedlist"><ul type="disc"><li>
<p>Parse and process the challenge sent by the target server in response to
request for a protected resource.</p>
</li><li>
<p>Provide properties of the processed challenge: the authentication scheme type
and its parameters, such the realm this authentication scheme is applicable to,
if available</p>
</li><li>
<p>Generate authorization string for the given set of credentials and the HTTP
request in response to the actual authorization challenge.</p>
</li></ul></div>
<p>Please note authentication schemes may be stateful involving a series of
challenge-response exchanges.</p>
<p>HttpClient ships with several <code class="interfacename">AuthScheme</code>
implementations:</p>
<div class="itemizedlist"><ul type="disc"><li>
<p>
<b>Basic:&nbsp;</b>
Basic authentication scheme as defined in RFC 2617. This authentication
scheme is insecure, as the credentials are transmitted in clear text.
Despite its insecurity Basic authentication scheme is perfectly adequate if
used in combination with the TLS/SSL encryption.
</p>
</li><li>
<p>
<b>Digest.&nbsp;</b>
Digest authentication scheme as defined in RFC 2617. Digest authentication
scheme is significantly more secure than Basic and can be a good choice for
those applications that do not want the overhead of full transport security
through TLS/SSL encryption.
</p>
</li><li>
<p>
<b>NTLM:&nbsp;</b>
NTLM is a proprietary authentication scheme developed by Microsoft and
optimized for Windows platforms. NTLM is believed to be more secure than
Digest. This scheme is requires an external NTLM engine to be functional.
For details please refer to the <code class="literal">NTLM_SUPPORT.txt</code> document
included with HttpClient distributions.
</p>
</li></ul></div>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="d4e869"></a>4.3.&nbsp;HTTP authentication parameters</h2></div></div></div>
<p>These are parameters that be used to customize HTTP authentication process and
behaviour of individual authentication schemes:</p>
<div class="itemizedlist"><ul type="disc"><li>
<p>
<b>'http.protocol.handle-authentication':&nbsp;</b>
defines whether authentication should be handled automatically. This
parameter expects a value of type <code class="classname">java.lang.Boolean</code>.
If this parameter is not set HttpClient will handle authentication
automatically.
</p>
</li><li>
<p>
<b>'http.auth.credential-charset':&nbsp;</b>
defines the charset to be used when encoding user credentials. This
parameter expects a value of type <code class="literal">java.lang.String</code>. If
this parameter is not set <code class="literal">US-ASCII</code> will be used.
</p>
</li></ul></div>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="d4e884"></a>4.4.&nbsp;Authentication scheme registry</h2></div></div></div>
<p>HttpClient maintains a registry of available authentication scheme using
<code class="classname">AuthSchemeRegistry</code> class. The following schemes are
registered per default:</p>
<div class="itemizedlist"><ul type="disc"><li>
<p>
<b>Basic:&nbsp;</b>
Basic authentication scheme
</p>
</li><li>
<p>
<b>Digest:&nbsp;</b>
Digest authentication scheme
</p>
</li></ul></div>
<p>Please note <code class="literal">NTLM</code> scheme is <span class="emphasis"><em>NOT</em></span> registered per
default. The <code class="literal">NTLM</code> cannot be enabled per default due to licensing and
legal reasons. For details on how to enable <code class="literal">NTLM</code> support please see
<a class="link" href="authentication.html#ntlm" title="4.8.&nbsp;NTLM Authentication">this</a> section. </p>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="d4e903"></a>4.5.&nbsp;Credentials provider</h2></div></div></div>
<p>Credentials providers are intended to maintain a set of user credentials and to be
able to produce user credentials for a particular authentication scope. Authentication
scope consists of a host name, a port number, a realm name and an authentication scheme
name. When registering credentials with the credentials provider one can provide a wild
card (any host, any port, any realm, any scheme) instead of a concrete attribute value.
The credentials provider is then expected to be able to find the closest match for a
particular scope if the direct match cannot be found.</p>
<p>HttpClient can work with any physical representation of a credentials provider that
implements the <code class="interfacename">CredentialsProvider</code> interface. The default
<code class="interfacename">CredentialsProvider</code> implementation called
<code class="classname">BasicCredentialsProvider</code> is a simple implementation backed by
a <code class="classname">java.util.HashMap</code>.</p>
<pre class="programlisting">
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope("somehost", AuthScope.ANY_PORT),
new UsernamePasswordCredentials("u1", "p1"));
credsProvider.setCredentials(
new AuthScope("somehost", 8080),
new UsernamePasswordCredentials("u2", "p2"));
credsProvider.setCredentials(
new AuthScope("otherhost", 8080, AuthScope.ANY_REALM, "ntlm"),
new UsernamePasswordCredentials("u3", "p3"));
 
System.out.println(credsProvider.getCredentials(
new AuthScope("somehost", 80, "realm", "basic")));
System.out.println(credsProvider.getCredentials(
new AuthScope("somehost", 8080, "realm", "basic")));
System.out.println(credsProvider.getCredentials(
new AuthScope("otherhost", 8080, "realm", "basic")));
System.out.println(credsProvider.getCredentials(
new AuthScope("otherhost", 8080, null, "ntlm")));
</pre>
<p>stdout &gt;</p>
<pre class="programlisting">
[principal: u1]
[principal: u2]
null
[principal: u3]
</pre>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="d4e914"></a>4.6.&nbsp;HTTP authentication and execution context</h2></div></div></div>
<p>HttpClient relies on the <code class="classname">AuthState</code> class to keep track of
detailed information about the state of the authentication process. HttpClient creates
two instances of <code class="classname">AuthState</code> in the course of HTTP request
execution: one for target host authentication and another one for proxy authentication.
In case the target server or the proxy require user authentication the respective
<code class="classname">AuthScope</code> instance will be populated with the
<code class="classname">AuthScope</code>, <code class="interfacename">AuthScheme</code> and
<code class="interfacename">Crednetials</code> used during the authentication process.
The <code class="classname">AuthState</code> can be examined in order to find out what kind of
authentication was requested, whether a matching
<code class="interfacename">AuthScheme</code> implementation was found and whether the
credentials provider managed to find user credentials for the given authentication
scope.</p>
<p>In the course of HTTP request execution HttpClient adds the following authentication
related objects to the execution context:</p>
<div class="itemizedlist"><ul type="disc"><li>
<p>
<b>'http.authscheme-registry':&nbsp;</b>
<code class="classname">AuthSchemeRegistry</code> instance representing the actual
authentication scheme registry. The value of this attribute set in the local
context takes precedence over the default one.
</p>
</li><li>
<p>
<b>'http.auth.credentials-provider':&nbsp;</b>
<code class="interfacename">CookieSpec</code> instance representing the actual
credentials provider. The value of this attribute set in the local context
takes precedence over the default one.
</p>
</li><li>
<p>
<b>'http.auth.target-scope':&nbsp;</b>
<code class="classname">AuthState</code> instance representing the actual target
authentication state. The value of this attribute set in the local context
takes precedence over the default one.
</p>
</li><li>
<p>
<b>'http.auth.proxy-scope':&nbsp;</b>
<code class="classname">AuthState</code> instance representing the actual proxy
authentication state. The value of this attribute set in the local context
takes precedence over the default one.
</p>
</li></ul></div>
<p>The local <code class="interfacename">HttpContext</code> object can be used to customize
the HTTP authentication context prior to request execution or examine its state after
the request has been executed:</p>
<pre class="programlisting">
HttpClient httpclient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpget = new HttpGet("http://localhost:8080/");
HttpResponse response = httpclient.execute(httpget, localContext);
 
AuthState proxyAuthState = (AuthState) localContext.getAttribute(
ClientContext.PROXY_AUTH_STATE);
System.out.println("Proxy auth scope: " + proxyAuthState.getAuthScope());
System.out.println("Proxy auth scheme: " + proxyAuthState.getAuthScheme());
System.out.println("Proxy auth credentials: " + proxyAuthState.getCredentials());
AuthState targetAuthState = (AuthState) localContext.getAttribute(
ClientContext.TARGET_AUTH_STATE);
System.out.println("Target auth scope: " + targetAuthState.getAuthScope());
System.out.println("Target auth scheme: " + targetAuthState.getAuthScheme());
System.out.println("Target auth credentials: " + targetAuthState.getCredentials());
</pre>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="d4e950"></a>4.7.&nbsp;Preemptive authentication</h2></div></div></div>
<p>HttpClient does not support preemptive authentication out of the box, because if
misused or used incorrectly the preemptive authentication can lead to significant
security issues, such as sending user credentials in clear text to an unauthorized third
party. Therefore, users are expected to evaluate potential benefits of preemptive
authentication versus security risks in the context of their specific application
environment and are required to add support for preemptive authentication using standard
HttpClient extension mechanisms such as protocol interceptors.</p>
<p>This is an example of a simple protocol interceptor that preemptively introduces an
instance of <code class="classname">BasicScheme</code> to the execution context, if no
authentication has been attempted yet. Please note that this interceptor must be added
to the protocol processing chain before the standard authentication interceptors.</p>
<pre class="programlisting">
HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
public void process(
final HttpRequest request,
final HttpContext context) throws HttpException, IOException {
AuthState authState = (AuthState) context.getAttribute(
ClientContext.TARGET_AUTH_STATE);
CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(
ClientContext.CREDS_PROVIDER);
HttpHost targetHost = (HttpHost) context.getAttribute(
ExecutionContext.HTTP_TARGET_HOST);
// If not auth scheme has been initialized yet
if (authState.getAuthScheme() == null) {
AuthScope authScope = new AuthScope(
targetHost.getHostName(),
targetHost.getPort());
// Obtain credentials matching the target host
Credentials creds = credsProvider.getCredentials(authScope);
// If found, generate BasicScheme preemptively
if (creds != null) {
authState.setAuthScheme(new BasicScheme());
authState.setCredentials(creds);
}
}
}
};
 
DefaultHttpClient httpclient = new DefaultHttpClient();
// Add as the very first interceptor in the protocol chain
httpclient.addRequestInterceptor(preemptiveAuth, 0);
</pre>
</div>
 
<div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="ntlm"></a>4.8.&nbsp;NTLM Authentication</h2></div></div></div>
<p>Currently HttpClient does not provide support for the NTLM authentication scheme out
of the box and probably never will. The reasons for that are legal rather than
technical. However, NTLM authentication can be enabled by using an external
<code class="literal">NTLM</code> engine such as <a class="ulink" href="http://jcifs.samba.org/" target="_top">JCIFS
</a> library developed by the <a class="ulink" href="http://www.samba.org/" target="_top">Samba</a>
project as a part of their Windows interoperability suite of programs. For details
please refer to the <code class="literal">NTLM_SUPPORT.txt</code> document included with
HttpClient distributions.
</p>
<div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="d4e963"></a>4.8.1.&nbsp;NTLM connection persistence</h3></div></div></div>
<p><code class="literal">NTLM</code> authentication scheme is significantly more expensive
in terms of computational overhead and performance impact than the standard
<code class="literal">Basic</code> and <code class="literal">Digest</code> schemes. This is likely to be
one of the main reasons why Microsoft chose to make <code class="literal">NTLM</code>
authentication scheme stateful. That is, once authenticated, the user identity is
associated with that connection for its entire life span. The stateful nature of
<code class="literal">NTLM</code> connections makes connection persistence more complex, as
for the obvious reason persistent <code class="literal">NTLM</code> connections may not be
re-used by users with a different user identity. The standard connection managers
shipped with HttpClient are fully capable of managing stateful connections. However,
it is critically important that logically related requests within the same session
use the same execution context in order to make them aware of the current user
identity. Otherwise, HttpClient will end up creating a new HTTP connection for each
HTTP request against <code class="literal">NTLM</code> protected resources. For detailed
discussion on stateful HTTP connections please refer to
<a class="link" href="advanced.html#stateful_conn" title="6.2.&nbsp;Stateful HTTP connections">this </a> section. </p>
<p>As <code class="literal">NTLM</code> connections are stateful it is generally recommended
to trigger <code class="literal">NTLM</code> authentication using a relatively cheap method,
such as <code class="literal">GET</code> or <code class="literal">HEAD</code>, and re-use the same
connection to execute more expensive methods, especially those enclose a request
entity, such as <code class="literal">POST</code> or <code class="literal">PUT</code>. </p>
<pre class="programlisting">
DefaultHttpClient httpclient = new DefaultHttpClient();
 
NTCredentials creds = new NTCredentials("user", "pwd", "myworkstation", "microsoft.com");
httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);
 
HttpHost target = new HttpHost("www.microsoft.com", 80, "http");
 
// Make sure the same context is used to execute logically related requests
HttpContext localContext = new BasicHttpContext();
 
// Execute a cheap method first. This will trigger NTLM authentication
HttpGet httpget = new HttpGet("/ntlm-protected/info");
HttpResponse response1 = httpclient.execute(target, httpget, localContext);
HttpEntity entity1 = response1.getEntity();
if (entity1 != null) {
entity1.consumeContent();
}
 
// Execute an expensive method next reusing the same context (and connection)
HttpPost httppost = new HttpPost("/ntlm-protected/form");
httppost.setEntity(new StringEntity("lots and lots of data"));
HttpResponse response2 = httpclient.execute(target, httppost, localContext);
HttpEntity entity2 = response2.getEntity();
if (entity2 != null) {
entity2.consumeContent();
}
</pre>
</div>
</div>
 
</div><div class="navfooter"><hr><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="statemgmt.html">Prev</a>&nbsp;</td><td width="20%" align="center">&nbsp;</td><td width="40%" align="right">&nbsp;<a accesskey="n" href="httpagent.html">Next</a></td></tr><tr><td width="40%" align="left" valign="top">Chapter&nbsp;3.&nbsp;HTTP state management&nbsp;</td><td width="20%" align="center"><a accesskey="h" href="index.html">Home</a></td><td width="40%" align="right" valign="top">&nbsp;Chapter&nbsp;5.&nbsp;HTTP client service</td></tr></table></div></body></html>
/ViaThinkSoft Java Utils/lib/httpcomponents-client-4.0.1/tutorial/html/fundamentals.html
0,0 → 1,906
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Chapter&nbsp;1.&nbsp;Fundamentals</title><link rel="stylesheet" href="css/hc-tutorial.css" type="text/css"><meta name="generator" content="DocBook XSL-NS Stylesheets V1.73.2"><link rel="start" href="index.html" title="HttpClient Tutorial"><link rel="up" href="index.html" title="HttpClient Tutorial"><link rel="prev" href="preface.html" title="Preface"><link rel="next" href="connmgmt.html" title="Chapter&nbsp;2.&nbsp;Connection management"></head><body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"><div xmlns:fo="http://www.w3.org/1999/XSL/Format" class="banner"><a class="bannerLeft" href="http://www.apache.org/" title="Apache Software Foundation"><img style="border:none;" src="images/asf_logo_wide.gif"></a><a class="bannerRight" href="http://hc.apache.org/httpcomponents-core/" title="Apache HttpComponents Core"><img style="border:none;" src="images/hc_logo.png"></a><div class="clear"></div></div><div class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="3" align="center">Chapter&nbsp;1.&nbsp;Fundamentals</th></tr><tr><td width="20%" align="left"><a accesskey="p" href="preface.html">Prev</a>&nbsp;</td><th width="60%" align="center">&nbsp;</th><td width="20%" align="right">&nbsp;<a accesskey="n" href="connmgmt.html">Next</a></td></tr></table><hr></div><div class="chapter" lang="en"><div class="titlepage"><div><div><h2 class="title"><a name="fundamentals"></a>Chapter&nbsp;1.&nbsp;Fundamentals</h2></div></div></div>
<div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="d4e37"></a>1.1.&nbsp;Request execution</h2></div></div></div>
<p> The most essential function of HttpClient is to execute HTTP methods. Execution of an
HTTP method involves one or several HTTP request / HTTP response exchanges, usually
handled internally by HttpClient. The user is expected to provide a request object to
execute and HttpClient is expected to transmit the request to the target server return a
corresponding response object, or throw an exception if execution was unsuccessful. </p>
<p> Quite naturally, the main entry point of the HttpClient API is the HttpClient
interface that defines the contract described above. </p>
<p>Here is an example of request execution process in its simplest form:</p>
<pre class="programlisting">
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://localhost/");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
int l;
byte[] tmp = new byte[2048];
while ((l = instream.read(tmp)) != -1) {
}
}
</pre>
<div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="d4e43"></a>1.1.1.&nbsp;HTTP request</h3></div></div></div>
<p>All HTTP requests have a request line consisting a method name, a request URI and
a HTTP protocol version.</p>
<p>HttpClient supports out of the box all HTTP methods defined in the HTTP/1.1
specification: <code class="literal">GET</code>, <code class="literal">HEAD</code>,
<code class="literal">POST</code>, <code class="literal">PUT</code>, <code class="literal">DELETE</code>,
<code class="literal">TRACE</code> and <code class="literal">OPTIONS</code>. There is a special
class for each method type.: <code class="classname">HttpGet</code>,
<code class="classname">HttpHead</code>, <code class="classname">HttpPost</code>,
<code class="classname">HttpPut</code>, <code class="classname">HttpDelete</code>,
<code class="classname">HttpTrace</code>, and <code class="classname">HttpOptions</code>.</p>
<p>The Request-URI is a Uniform Resource Identifier that identifies the resource upon
which to apply the request. HTTP request URIs consist of a protocol scheme, host
name, optional port, resource path, optional query, and optional fragment.</p>
<pre class="programlisting">
HttpGet httpget = new HttpGet(
"http://www.google.com/search?hl=en&amp;q=httpclient&amp;btnG=Google+Search&amp;aq=f&amp;oq=");
</pre>
<p>HttpClient provides a number of utility methods to simplify creation and
modification of request URIs.</p>
<p>URI can be assembled programmatically:</p>
<pre class="programlisting">
URI uri = URIUtils.createURI("http", "www.google.com", -1, "/search",
"q=httpclient&amp;btnG=Google+Search&amp;aq=f&amp;oq=", null);
HttpGet httpget = new HttpGet(uri);
System.out.println(httpget.getURI());
</pre>
<p>stdout &gt;</p>
<pre class="programlisting">
http://www.google.com/search?q=httpclient&amp;btnG=Google+Search&amp;aq=f&amp;oq=
</pre>
<p>Query string can also be generated from individual parameters:</p>
<pre class="programlisting">
List&lt;NameValuePair&gt; qparams = new ArrayList&lt;NameValuePair&gt;();
qparams.add(new BasicNameValuePair("q", "httpclient"));
qparams.add(new BasicNameValuePair("btnG", "Google Search"));
qparams.add(new BasicNameValuePair("aq", "f"));
qparams.add(new BasicNameValuePair("oq", null));
URI uri = URIUtils.createURI("http", "www.google.com", -1, "/search",
URLEncodedUtils.format(qparams, "UTF-8"), null);
HttpGet httpget = new HttpGet(uri);
System.out.println(httpget.getURI());
</pre>
<p>stdout &gt;</p>
<pre class="programlisting">
http://www.google.com/search?q=httpclient&amp;btnG=Google+Search&amp;aq=f&amp;oq=
</pre>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="d4e72"></a>1.1.2.&nbsp;HTTP response</h3></div></div></div>
<p>HTTP response is a message sent by the server back to the client after having
received and interpreted a request message. The first line of that message consists
of the protocol version followed by a numeric status code and its associated textual
phrase.</p>
<pre class="programlisting">
HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1,
HttpStatus.SC_OK, "OK");
 
System.out.println(response.getProtocolVersion());
System.out.println(response.getStatusLine().getStatusCode());
System.out.println(response.getStatusLine().getReasonPhrase());
System.out.println(response.getStatusLine().toString());
</pre>
<p>stdout &gt;</p>
<pre class="programlisting">
HTTP/1.1
200
OK
HTTP/1.1 200 OK
</pre>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="d4e78"></a>1.1.3.&nbsp;Working with message headers</h3></div></div></div>
<p>An HTTP message can contain a number of headers describing properties of the
message such as the content length, content type and so on. HttpClient provides
methods to retrieve, add, remove and enumerate headers.</p>
<pre class="programlisting">
HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1,
HttpStatus.SC_OK, "OK");
response.addHeader("Set-Cookie",
"c1=a; path=/; domain=localhost");
response.addHeader("Set-Cookie",
"c2=b; path=\"/\", c3=c; domain=\"localhost\"");
Header h1 = response.getFirstHeader("Set-Cookie");
System.out.println(h1);
Header h2 = response.getLastHeader("Set-Cookie");
System.out.println(h2);
Header[] hs = response.getHeaders("Set-Cookie");
System.out.println(hs.length);
</pre>
<p>stdout &gt;</p>
<pre class="programlisting">
Set-Cookie: c1=a; path=/; domain=localhost
Set-Cookie: c2=b; path="/", c3=c; domain="localhost"
2
</pre>
<p>The most efficient way to obtain all headers of a given type is by using the
<code class="interfacename">HeaderIterator</code> interface.</p>
<pre class="programlisting">
HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1,
HttpStatus.SC_OK, "OK");
response.addHeader("Set-Cookie",
"c1=a; path=/; domain=localhost");
response.addHeader("Set-Cookie",
"c2=b; path=\"/\", c3=c; domain=\"localhost\"");
 
HeaderIterator it = response.headerIterator("Set-Cookie");
 
while (it.hasNext()) {
System.out.println(it.next());
}
</pre>
<p>stdout &gt;</p>
<pre class="programlisting">
Set-Cookie: c1=a; path=/; domain=localhost
Set-Cookie: c2=b; path="/", c3=c; domain="localhost"
</pre>
<p>It also provides convenience methods to parse HTTP messages into individual header
elements.</p>
<pre class="programlisting">
HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1,
HttpStatus.SC_OK, "OK");
response.addHeader("Set-Cookie",
"c1=a; path=/; domain=localhost");
response.addHeader("Set-Cookie",
"c2=b; path=\"/\", c3=c; domain=\"localhost\"");
 
HeaderElementIterator it = new BasicHeaderElementIterator(
response.headerIterator("Set-Cookie"));
 
while (it.hasNext()) {
HeaderElement elem = it.nextElement();
System.out.println(elem.getName() + " = " + elem.getValue());
NameValuePair[] params = elem.getParameters();
for (int i = 0; i &lt; params.length; i++) {
System.out.println(" " + params[i]);
}
}
</pre>
<p>stdout &gt;</p>
<pre class="programlisting">
c1 = a
path=/
domain=localhost
c2 = b
path=/
c3 = c
domain=localhost
</pre>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="d4e93"></a>1.1.4.&nbsp;HTTP entity</h3></div></div></div>
<p>HTTP messages can carry a content entity associated with the request or response.
Entities can be found in some requests and in some responses, as they are optional.
Requests that use entities are referred to as entity enclosing requests. The HTTP
specification defines two entity enclosing methods: <code class="literal">POST</code> and
<code class="literal">PUT</code>. Responses are usually expected to enclose a content
entity. There are exceptions to this rule such as responses to
<code class="literal">HEAD</code> method and <code class="literal">204 No Content</code>,
<code class="literal">304 Not Modified</code>, <code class="literal">205 Reset Content</code>
responses.</p>
<p>HttpClient distinguishes three kinds of entities, depending on where their content
originates:</p>
<div class="itemizedlist"><ul type="disc"><li>
<p>
<b>streamed:&nbsp;</b>
The content is received from a stream, or generated on the fly. In
particular, this category includes entities being received from HTTP
responses. Streamed entities are generally not repeatable.
</p>
</li><li>
<p>
<b>self-contained:&nbsp;</b>
The content is in memory or obtained by means that are independent
from a connection or other entity. Self-contained entities are generally
repeatable. This type of entities will be mostly used for entity
enclosing HTTP requests.
</p>
</li><li>
<p>
<b>wrapping:&nbsp;</b>
The content is obtained from another entity.
</p>
</li></ul></div>
<p>This distinction is important for connection management when streaming out content
from an HTTP response. For request entities that are created by an application and
only sent using HttpClient, the difference between streamed and self-contained is of
little importance. In that case, it is suggested to consider non-repeatable entities
as streamed, and those that are repeatable as self-contained.</p>
<div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="d4e117"></a>1.1.4.1.&nbsp;Repeatable entities</h4></div></div></div>
<p>An entity can be repeatable, meaning its content can be read more than once.
This is only possible with self contained entities (like
<code class="classname">ByteArrayEntity</code> or
<code class="classname">StringEntity</code>)</p>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="d4e122"></a>1.1.4.2.&nbsp;Using HTTP entities</h4></div></div></div>
<p>Since an entity can represent both binary and character content, it has
support for character encodings (to support the latter, ie. character
content).</p>
<p>The entity is created when executing a request with enclosed content or when
the request was successful and the response body is used to send the result back
to the client.</p>
<p>To read the content from the entity, one can either retrieve the input stream
via the <code class="methodname">HttpEntity#getContent()</code> method, which returns
an <code class="classname">java.io.InputStream</code>, or one can supply an output
stream to the <code class="methodname">HttpEntity#writeTo(OutputStream)</code> method,
which will return once all content has been written to the given stream.</p>
<p>When the entity has been received with an incoming message, the methods
<code class="methodname">HttpEntity#getContentType()</code> and
<code class="methodname">HttpEntity#getContentLength()</code> methods can be used
for reading the common metadata such as <code class="literal">Content-Type</code> and
<code class="literal">Content-Length</code> headers (if they are available). Since the
<code class="literal">Content-Type</code> header can contain a character encoding for
text mime-types like text/plain or text/html, the
<code class="methodname">HttpEntity#getContentEncoding()</code> method is used to
read this information. If the headers aren't available, a length of -1 will be
returned, and NULL for the content type. If the <code class="literal">Content-Type</code>
header is available, a <code class="interfacename">Header</code> object will be
returned.</p>
<p>When creating an entity for a outgoing message, this meta data has to be
supplied by the creator of the entity.</p>
<pre class="programlisting">
StringEntity myEntity = new StringEntity("important message",
"UTF-8");
 
System.out.println(myEntity.getContentType());
System.out.println(myEntity.getContentLength());
System.out.println(EntityUtils.getContentCharSet(myEntity));
System.out.println(EntityUtils.toString(myEntity));
System.out.println(EntityUtils.toByteArray(myEntity).length);
</pre>
<p>stdout &gt;</p>
<pre class="programlisting">
Content-Type: text/plain; charset=UTF-8
17
UTF-8
important message
17
</pre>
</div>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="d4e143"></a>1.1.5.&nbsp;Ensuring release of low level resources</h3></div></div></div>
<p>When finished with a response entity, it's important to ensure that all entity
content has been fully consumed, so that the connection could be safely returned to
the connection pool and re-used by the connection manager for subsequent requests.
The easiest way to do so is to call the
<code class="methodname">HttpEntity#consumeContent(</code>) method to consume any
available content on the stream. HttpClient will automatically release the
underlying connection back to the connection manager as soon as it detects that the
end of the content stream has been reached. The
<code class="methodname">HttpEntity#consumeContent()</code> method is safe to call more
than once.</p>
<p>There can be situations, however, when only a small portion of the entire response
content needs to be retrieved and the performance penalty for consuming the
remaining content and making the connection reusable is too high, one can simply
terminate the request by calling <code class="methodname">HttpUriRequest#abort()</code>
method.</p>
<pre class="programlisting">
HttpGet httpget = new HttpGet("http://localhost/");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
int byteOne = instream.read();
int byteTwo = instream.read();
// Do not need the rest
httpget.abort();
}
</pre>
<p>The connection will not be reused, but all level resources held by it will be
correctly deallocated.</p>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="d4e152"></a>1.1.6.&nbsp;Consuming entity content</h3></div></div></div>
<p>The recommended way to consume content of an entity is by using its
<code class="methodname">HttpEntity#getContent()</code> or
<code class="methodname">HttpEntity#writeTo(OutputStream)</code> methods. HttpClient
also comes with the <code class="classname">EntityUtils</code> class, which exposes several
static methods to more easily read the content or information from an entity.
Instead of reading the <code class="classname">java.io.InputStream</code> directly, one can
retrieve the whole content body in a string / byte array by using the methods from
this class. However, the use of <code class="classname">EntityUtils</code> is
strongly discouraged unless the response entities originate from a trusted HTTP
server and are known to be of limited length.</p>
<pre class="programlisting">
HttpGet httpget = new HttpGet("http://localhost/");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
long len = entity.getContentLength();
if (len != -1 &amp;&amp; len &lt; 2048) {
System.out.println(EntityUtils.toString(entity));
} else {
// Stream content out
}
}
</pre>
<p>In some situations it may be necessary to be able to read entity content more than
once. In this case entity content must be buffered in some way, either in memory or
on disk. The simplest way to accomplish that is by wrapping the original entity with
the <code class="classname">BufferedHttpEntity</code> class. This will cause the content of
the original entity to be read into a in-memory buffer. In all other ways the entity
wrapper will be have the original one.</p>
<pre class="programlisting">
HttpGet httpget = new HttpGet("http://localhost/");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
entity = new BufferedHttpEntity(entity);
}
</pre>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="d4e164"></a>1.1.7.&nbsp;Producing entity content</h3></div></div></div>
<p>HttpClient provides several classes that can be used to efficiently stream out
content though HTTP connections. Instances of those classes can be associated with
entity enclosing requests such as <code class="literal">POST</code> and <code class="literal">PUT</code>
in order to enclose entity content into outgoing HTTP requests. HttpClient provides
several classes for most common data containers such as string, byte array, input
stream, and file: <code class="classname">StringEntity</code>,
<code class="classname">ByteArrayEntity</code>,
<code class="classname">InputStreamEntity</code>, and
<code class="classname">FileEntity</code>.</p>
<pre class="programlisting">
File file = new File("somefile.txt");
FileEntity entity = new FileEntity(file, "text/plain; charset=\"UTF-8\"");
 
HttpPost httppost = new HttpPost("http://localhost/action.do");
httppost.setEntity(entity);
</pre>
<p>Please note <code class="classname">InputStreamEntity</code> is not repeatable, because it
can only read from the underlying data stream once. Generally it is recommended to
implement a custom <code class="interfacename">HttpEntity</code> class which is
self-contained instead of using generic <code class="classname">InputStreamEntity</code>.
<code class="classname">FileEntity</code> can be a good starting point.</p>
<div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="d4e179"></a>1.1.7.1.&nbsp;Dynamic content entities</h4></div></div></div>
<p>Often HTTP entities need to be generated dynamically based a particular
execution context. HttpClient provides support for dynamic entities by using
<code class="classname">EntityTemplate</code> entity class and
<code class="interfacename">ContentProducer</code> interface. Content producers
are objects which produce their content on demand, by writing it out to an
output stream. They are expected to be able produce their content every time
they are requested to do so. So entities created with
<code class="classname">EntityTemplate</code> are generally self-contained and
repeatable.</p>
<pre class="programlisting">
ContentProducer cp = new ContentProducer() {
public void writeTo(OutputStream outstream) throws IOException {
Writer writer = new OutputStreamWriter(outstream, "UTF-8");
writer.write("&lt;response&gt;");
writer.write(" &lt;content&gt;");
writer.write(" important stuff");
writer.write(" &lt;/content&gt;");
writer.write("&lt;/response&gt;");
writer.flush();
}
};
HttpEntity entity = new EntityTemplate(cp);
HttpPost httppost = new HttpPost("http://localhost/handler.do");
httppost.setEntity(entity);
</pre>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="d4e186"></a>1.1.7.2.&nbsp;HTML forms</h4></div></div></div>
<p>Many applications frequently need to simulate the process of submitting an
HTML form, for instance, in order to log in to a web application or submit input
data. HttpClient provides special entity class
<code class="classname">UrlEncodedFormEntity</code> to facilitate the
process.</p>
<pre class="programlisting">
List&lt;NameValuePair&gt; formparams = new ArrayList&lt;NameValuePair&gt;();
formparams.add(new BasicNameValuePair("param1", "value1"));
formparams.add(new BasicNameValuePair("param2", "value2"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
HttpPost httppost = new HttpPost("http://localhost/handler.do");
httppost.setEntity(entity);
</pre>
<p>This <code class="classname">UrlEncodedFormEntity</code> instance will use the so
called URL encoding to encode parameters and produce the following
content:</p>
<pre class="programlisting">
param1=value1&amp;param2=value2
</pre>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="d4e194"></a>1.1.7.3.&nbsp;Content chunking</h4></div></div></div>
<p>Generally it is recommended to let HttpClient choose the most appropriate
transfer encoding based on the properties of the HTTP message being transferred.
It is possible, however, to inform HttpClient that the chunk coding is preferred
by setting <code class="methodname">HttpEntity#setChunked()</code> to true. Please note
that HttpClient will use this flag as a hint only. This value well be ignored
when using HTTP protocol versions that do not support chunk coding, such as
HTTP/1.0.</p>
<pre class="programlisting">
StringEntity entity = new StringEntity("important message",
"text/plain; charset=\"UTF-8\"");
entity.setChunked(true);
HttpPost httppost = new HttpPost("http://localhost/acrtion.do");
httppost.setEntity(entity);
</pre>
</div>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="d4e199"></a>1.1.8.&nbsp;Response handlers</h3></div></div></div>
<p>The simplest and the most convenient way to handle responses is by using
<code class="interfacename">ResponseHandler</code> interface. This method completely
relieves the user from having to worry about connection management. When using a
<code class="interfacename">ResponseHandler</code> HttpClient will automatically
take care of ensuring release of the connection back to the connection manager
regardless whether the request execution succeeds or causes an exception.</p>
<pre class="programlisting">
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://localhost/");
 
ResponseHandler&lt;byte[]&gt; handler = new ResponseHandler&lt;byte[]&gt;() {
public byte[] handleResponse(
HttpResponse response) throws ClientProtocolException, IOException {
HttpEntity entity = response.getEntity();
if (entity != null) {
return EntityUtils.toByteArray(entity);
} else {
return null;
}
}
};
 
byte[] response = httpclient.execute(httpget, handler);
</pre>
</div>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="d4e205"></a>1.2.&nbsp;HTTP execution context</h2></div></div></div>
<p>Originally HTTP has been designed as a stateless, response-request oriented protocol.
However, real world applications often need to be able to persist state information
through several logically related request-response exchanges. In order to enable
applications to maintain a processing state HttpClient allows HTTP requests to be
executed within a particular execution context, referred to as HTTP context. Multiple
logically related requests can participate in a logical session if the same context is
reused between consecutive requests. HTTP context functions similarly to
<code class="interfacename">java.util.Map&lt;String, Object&gt;</code>. It is
simply a collection of arbitrary named values. Application can populate context
attributes prior to a request execution or examine the context after the execution has
been completed.</p>
<p>In the course of HTTP request execution HttpClient adds the following attributes to
the execution context:</p>
<div class="itemizedlist"><ul type="disc"><li>
<p>
<b>'http.connection':&nbsp;</b>
<code class="interfacename">HttpConnection</code> instance representing the
actual connection to the target server.
</p>
</li><li>
<p>
<b>'http.target_host':&nbsp;</b>
<code class="classname">HttpHost</code> instance representing the connection
target.
</p>
</li><li>
<p>
<b>'http.proxy_host':&nbsp;</b>
<code class="classname">HttpHost</code> instance representing the connection
proxy, if used
</p>
</li><li>
<p>
<b>'http.request':&nbsp;</b>
<code class="interfacename">HttpRequest</code> instance representing the
actual HTTP request.
</p>
</li><li>
<p>
<b>'http.response':&nbsp;</b>
<code class="interfacename">HttpResponse</code> instance representing the
actual HTTP response.
</p>
</li><li>
<p>
<b>'http.request_sent':&nbsp;</b>
<code class="classname">java.lang.Boolean</code> object representing the flag
indicating whether the actual request has been fully transmitted to the
connection target.
</p>
</li></ul></div>
<p>For instance, in order to determine the final redirect target, one can examine the
value of the <code class="literal">http.target_host</code> attribute after the request
execution:</p>
<pre class="programlisting">
DefaultHttpClient httpclient = new DefaultHttpClient();
 
HttpContext localContext = new BasicHttpContext();
HttpGet httpget = new HttpGet("http://www.google.com/");
 
HttpResponse response = httpclient.execute(httpget, localContext);
 
HttpHost target = (HttpHost) localContext.getAttribute(
ExecutionContext.HTTP_TARGET_HOST);
 
System.out.println("Final target: " + target);
 
HttpEntity entity = response.getEntity();
if (entity != null) {
entity.consumeContent();
}
</pre>
<p>stdout &gt;</p>
<pre class="programlisting">
Final target: http://www.google.ch
</pre>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="d4e246"></a>1.3.&nbsp;Exception handling</h2></div></div></div>
<p>HttpClient can throw two types of exceptions:
<code class="exceptionname">java.io.IOException</code> in case of an I/O failure such as
socket timeout or an socket reset and <code class="exceptionname">HttpException</code> that
signals an HTTP failure such as a violation of the HTTP protocol. Usually I/O errors are
considered non-fatal and recoverable, whereas HTTP protocol errors are considered fatal
and cannot be automatically recovered from.</p>
<div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="d4e251"></a>1.3.1.&nbsp;HTTP transport safety</h3></div></div></div>
<p>It is important to understand that the HTTP protocol is not well suited for all
types of applications. HTTP is a simple request/response oriented protocol which was
initially designed to support static or dynamically generated content retrieval. It
has never been intended to support transactional operations. For instance, the HTTP
server will consider its part of the contract fulfilled if it succeeds in receiving
and processing the request, generating a response and sending a status code back to
the client. The server will make no attempts to roll back the transaction if the
client fails to receive the response in its entirety due to a read timeout, a
request cancellation or a system crash. If the client decides to retry the same
request, the server will inevitably end up executing the same transaction more than
once. In some cases this may lead to application data corruption or inconsistent
application state.</p>
<p>Even though HTTP has never been designed to support transactional processing, it
can still be used as a transport protocol for mission critical applications provided
certain conditions are met. To ensure HTTP transport layer safety the system must
ensure the idempotency of HTTP methods on the application layer.</p>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="d4e255"></a>1.3.2.&nbsp;Idempotent methods</h3></div></div></div>
<p>HTTP/1.1 specification defines idempotent method as</p>
<p>
[<span class="citation">Methods can also have the property of "idempotence" in
that (aside from error or expiration issues) the side-effects of N &gt; 0
identical requests is the same as for a single request</span>]
</p>
<p>In other words the application ought to ensure that it is prepared to deal with
the implications of multiple execution of the same method. This can be achieved, for
instance, by providing a unique transaction id and by other means of avoiding
execution of the same logical operation.</p>
<p>Please note that this problem is not specific to HttpClient. Browser based
applications are subject to exactly the same issues related to HTTP methods
non-idempotency.</p>
<p>HttpClient assumes non-entity enclosing methods such as <code class="literal">GET</code> and
<code class="literal">HEAD</code> to be idempotent and entity enclosing methods such as
<code class="literal">POST</code> and <code class="literal">PUT</code> to be not.</p>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="d4e267"></a>1.3.3.&nbsp;Automatic exception recovery</h3></div></div></div>
<p>By default HttpClient attempts to automatically recover from I/O exceptions. The
default auto-recovery mechanism is limited to just a few exceptions that are known
to be safe.</p>
<div class="itemizedlist"><ul type="disc"><li>
<p>HttpClient will make no attempt to recover from any logical or HTTP
protocol errors (those derived from
<code class="exceptionname">HttpException</code> class).</p>
</li><li>
<p>HttpClient will automatically retry those methods that are assumed to be
idempotent.</p>
</li><li>
<p>HttpClient will automatically retry those methods that fail with a
transport exception while the HTTP request is still being transmitted to the
target server (i.e. the request has not been fully transmitted to the
server).</p>
</li><li>
<p>HttpClient will automatically retry those methods that have been fully
transmitted to the server, but the server failed to respond with an HTTP
status code (the server simply drops the connection without sending anything
back). In this case it is assumed that the request has not been processed by
the server and the application state has not changed. If this assumption may
not hold true for the web server your application is targeting it is highly
recommended to provide a custom exception handler.</p>
</li></ul></div>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="d4e280"></a>1.3.4.&nbsp;Request retry handler</h3></div></div></div>
<p>In order to enable a custom exception recovery mechanism one should provide an
implementation of the <code class="interfacename">HttpRequestRetryHandler</code>
interface.</p>
<pre class="programlisting">
DefaultHttpClient httpclient = new DefaultHttpClient();
 
HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler() {
 
public boolean retryRequest(
IOException exception,
int executionCount,
HttpContext context) {
if (executionCount &gt;= 5) {
// Do not retry if over max retry count
return false;
}
if (exception instanceof NoHttpResponseException) {
// Retry if the server dropped connection on us
return true;
}
if (exception instanceof SSLHandshakeException) {
// Do not retry on SSL handshake exception
return false;
}
HttpRequest request = (HttpRequest) context.getAttribute(
ExecutionContext.HTTP_REQUEST);
boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
if (idempotent) {
// Retry if the request is considered idempotent
return true;
}
return false;
}
 
};
 
httpclient.setHttpRequestRetryHandler(myRetryHandler);
</pre>
</div>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="d4e285"></a>1.4.&nbsp;Aborting requests</h2></div></div></div>
<p>In some situations HTTP request execution fail to complete within the expected time
frame due to high load on the target server or too many concurrent requests issued on
the client side. In such cases it may be necessary to terminate the request prematurely
and unblock the execution thread blocked in a I/O operation. HTTP requests being
executed by HttpClient can be aborted at any stage of execution by invoking
<code class="methodname">HttpUriRequest#abort()</code> method. This method is thread-safe
and can be called from any thread. When an HTTP request is aborted its execution thread
blocked in an I/O operation is guaranteed to unblock by throwing a
<code class="exceptionname">InterruptedIOException</code></p>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="d4e290"></a>1.5.&nbsp;HTTP protocol interceptors</h2></div></div></div>
<p>HTTP protocol interceptor is a routine that implements a specific aspect of the HTTP
protocol. Usually protocol interceptors are expected to act upon one specific header or
a group of related headers of the incoming message or populate the outgoing message with
one specific header or a group of related headers. Protocol interceptors can also
manipulate content entities enclosed with messages, transparent content compression /
decompression being a good example. Usually this is accomplished by using the
'Decorator' pattern where a wrapper entity class is used to decorate the original
entity. Several protocol interceptors can be combined to form one logical unit.</p>
<p>Protocol interceptors can collaborate by sharing information - such as a processing
state - through the HTTP execution context. Protocol interceptors can use HTTP context
to store a processing state for one request or several consecutive requests.</p>
<p>Usually the order in which interceptors are executed should not matter as long as they
do not depend on a particular state of the execution context. If protocol interceptors
have interdependencies and therefore must be executed in a particular order, they should
be added to the protocol processor in the same sequence as their expected execution
order.</p>
<p>Protocol interceptors must be implemented as thread-safe. Similarly to servlets,
protocol interceptors should not use instance variables unless access to those variables
is synchronized.</p>
<p>This is an example of how local context can be used to persist a processing state
between consecutive requests:</p>
<pre class="programlisting">
DefaultHttpClient httpclient = new DefaultHttpClient();
 
HttpContext localContext = new BasicHttpContext();
 
AtomicInteger count = new AtomicInteger(1);
 
localContext.setAttribute("count", count);
 
httpclient.addRequestInterceptor(new HttpRequestInterceptor() {
 
public void process(
final HttpRequest request,
final HttpContext context) throws HttpException, IOException {
AtomicInteger count = (AtomicInteger) context.getAttribute("count");
request.addHeader("Count", Integer.toString(count.getAndIncrement()));
}
});
 
HttpGet httpget = new HttpGet("http://localhost/");
for (int i = 0; i &lt; 10; i++) {
HttpResponse response = httpclient.execute(httpget, localContext);
HttpEntity entity = response.getEntity();
if (entity != null) {
entity.consumeContent();
}
}
</pre>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="d4e298"></a>1.6.&nbsp;HTTP parameters</h2></div></div></div>
<p>HttpParams interface represents a collection of immutable values that define a runtime
behavior of a component. In many ways <code class="interfacename">HttpParams</code> is
similar to <code class="interfacename">HttpContext</code>. The main distinction between the
two lies in their use at runtime. Both interfaces represent a collection of objects that
are organized as a map of keys to object values, but serve distinct purposes:</p>
<div class="itemizedlist"><ul type="disc"><li>
<p><code class="interfacename">HttpParams</code> is intended to contain simple
objects: integers, doubles, strings, collections and objects that remain
immutable at runtime.</p>
</li><li>
<p>
<code class="interfacename">HttpParams</code> is expected to be used in the 'write
once - ready many' mode. <code class="interfacename">HttpContext</code> is intended
to contain complex objects that are very likely to mutate in the course of HTTP
message processing. </p>
</li><li>
<p>The purpose of <code class="interfacename">HttpParams</code> is to define a
behavior of other components. Usually each complex component has its own
<code class="interfacename">HttpParams</code> object. The purpose of
<code class="interfacename">HttpContext</code> is to represent an execution
state of an HTTP process. Usually the same execution context is shared among
many collaborating objects.</p>
</li></ul></div>
<div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="d4e316"></a>1.6.1.&nbsp;Parameter hierarchies</h3></div></div></div>
<p>In the course of HTTP request execution <code class="interfacename">HttpParams</code>
of the <code class="interfacename">HttpRequest</code> object are linked together with
<code class="interfacename">HttpParams</code> of the
<code class="interfacename">HttpClient</code> instance used to execute the request.
This enables parameters set at the HTTP request level take precedence over
<code class="interfacename">HttpParams</code> set at the HTTP client level. The
recommended practice is to set common parameters shared by all HTTP requests at the
HTTP client level and selectively override specific parameters at the HTTP request
level.</p>
<pre class="programlisting">
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
HttpVersion.HTTP_1_0);
httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET,
"UTF-8");
 
HttpGet httpget = new HttpGet("http://www.google.com/");
httpget.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
HttpVersion.HTTP_1_1);
httpget.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE,
Boolean.FALSE);
 
httpclient.addRequestInterceptor(new HttpRequestInterceptor() {
 
public void process(
final HttpRequest request,
final HttpContext context) throws HttpException, IOException {
System.out.println(request.getParams().getParameter(
CoreProtocolPNames.PROTOCOL_VERSION));
System.out.println(request.getParams().getParameter(
CoreProtocolPNames.HTTP_CONTENT_CHARSET));
System.out.println(request.getParams().getParameter(
CoreProtocolPNames.USE_EXPECT_CONTINUE));
System.out.println(request.getParams().getParameter(
CoreProtocolPNames.STRICT_TRANSFER_ENCODING));
}
});
</pre>
<p>stdout &gt;</p>
<pre class="programlisting">
HTTP/1.1
UTF-8
false
null
</pre>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="d4e327"></a>1.6.2.&nbsp;HTTP parameters beans</h3></div></div></div>
<p><code class="interfacename">HttpParams</code> interface allows for a great deal of
flexibility in handling configuration of components. Most importantly, new
parameters can be introduced without affecting binary compatibility with older
versions. However, <code class="interfacename">HttpParams</code> also has a certain
disadvantage compared to regular Java beans:
<code class="interfacename">HttpParams</code> cannot be assembled using a DI
framework. To mitigate the limitation, HttpClient includes a number of bean classes
that can used in order to initialize <code class="interfacename">HttpParams</code>
objects using standard Java bean conventions.</p>
<pre class="programlisting">
HttpParams params = new BasicHttpParams();
HttpProtocolParamBean paramsBean = new HttpProtocolParamBean(params);
paramsBean.setVersion(HttpVersion.HTTP_1_1);
paramsBean.setContentCharset("UTF-8");
paramsBean.setUseExpectContinue(true);
 
System.out.println(params.getParameter(
CoreProtocolPNames.PROTOCOL_VERSION));
System.out.println(params.getParameter(
CoreProtocolPNames.HTTP_CONTENT_CHARSET));
System.out.println(params.getParameter(
CoreProtocolPNames.USE_EXPECT_CONTINUE));
System.out.println(params.getParameter(
CoreProtocolPNames.USER_AGENT));
</pre>
<p>stdout &gt;</p>
<pre class="programlisting">
HTTP/1.1
UTF-8
false
null
</pre>
</div>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="d4e337"></a>1.7.&nbsp;HTTP request execution parameters</h2></div></div></div>
<p>These are parameters that can impact the process of request execution:</p>
<div class="itemizedlist"><ul type="disc"><li>
<p>
<b>'http.protocol.version':&nbsp;</b>
defines HTTP protocol version used if not set explicitly on the request
object. This parameter expects a value of type
<code class="interfacename">ProtocolVersion</code>. If this parameter is not
set HTTP/1.1 will be used.
</p>
</li><li>
<p>
<b>'http.protocol.element-charset':&nbsp;</b>
defines the charset to be used for encoding HTTP protocol elements. This
parameter expects a value of type <code class="classname">java.lang.String</code>.
If this parameter is not set <code class="literal">US-ASCII</code> will be
used.
</p>
</li><li>
<p>
<b>'http.protocol.content-charset':&nbsp;</b>
defines the charset to be used per default for content body coding. This
parameter expects a value of type <code class="classname">java.lang.String</code>.
If this parameter is not set <code class="literal">ISO-8859-1</code> will be
used.
</p>
</li><li>
<p>
<b>'http.useragent':&nbsp;</b>
defines the content of the <code class="literal">User-Agent</code> header. This
parameter expects a value of type <code class="classname">java.lang.String</code>.
If this parameter is not set, HttpClient will automatically generate a value
for it.
</p>
</li><li>
<p>
<b>'http.protocol.strict-transfer-encoding':&nbsp;</b>
defines whether responses with an invalid
<code class="literal">Transfer-Encoding</code> header should be rejected. This
parameter expects a value of type <code class="classname">java.lang.Boolean</code>.
If this parameter is not set invalid <code class="literal">Transfer-Encoding</code>
values will be ignored.
</p>
</li><li>
<p>
<b>'http.protocol.expect-continue':&nbsp;</b>
activates <code class="literal">Expect: 100-Continue</code> handshake for the entity
enclosing methods. The purpose of the <code class="literal">Expect:
100-Continue</code> handshake is to allow the client that is sending
a request message with a request body to determine if the origin server is
willing to accept the request (based on the request headers) before the
client sends the request body. The use of the <code class="literal">Expect:
100-continue</code> handshake can result in a noticeable performance
improvement for entity enclosing requests (such as <code class="literal">POST</code>
and <code class="literal">PUT</code>) that require the target server's authentication.
<code class="literal">Expect: 100-continue</code> handshake should be used with
caution, as it may cause problems with HTTP servers and proxies that do not
support HTTP/1.1 protocol. This parameter expects a value of type
<code class="classname">java.lang.Boolean</code>. If this parameter is not set
HttpClient will attempt to use the handshake.
</p>
</li><li>
<p>
<b>'http.protocol.wait-for-continue':&nbsp;</b>
defines the maximum period of time in milliseconds the client should spend
waiting for a <code class="literal">100-continue</code> response. This parameter
expects a value of type <code class="classname">java.lang.Integer</code>. If this
parameter is not set HttpClient will wait 3 seconds for a confirmation
before resuming the transmission of the request body.
</p>
</li></ul></div>
</div>
</div><div class="navfooter"><hr><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="preface.html">Prev</a>&nbsp;</td><td width="20%" align="center">&nbsp;</td><td width="40%" align="right">&nbsp;<a accesskey="n" href="connmgmt.html">Next</a></td></tr><tr><td width="40%" align="left" valign="top">Preface&nbsp;</td><td width="20%" align="center"><a accesskey="h" href="index.html">Home</a></td><td width="40%" align="right" valign="top">&nbsp;Chapter&nbsp;2.&nbsp;Connection management</td></tr></table></div></body></html>
/ViaThinkSoft Java Utils/lib/httpcomponents-client-4.0.1/tutorial/html/images/asf_logo_wide.gif
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/ViaThinkSoft Java Utils/lib/httpcomponents-client-4.0.1/tutorial/html/images/hc_logo.png
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/ViaThinkSoft Java Utils/lib/httpcomponents-client-4.0.1/tutorial/html/connmgmt.html
0,0 → 1,769
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Chapter&nbsp;2.&nbsp;Connection management</title><link rel="stylesheet" href="css/hc-tutorial.css" type="text/css"><meta name="generator" content="DocBook XSL-NS Stylesheets V1.73.2"><link rel="start" href="index.html" title="HttpClient Tutorial"><link rel="up" href="index.html" title="HttpClient Tutorial"><link rel="prev" href="fundamentals.html" title="Chapter&nbsp;1.&nbsp;Fundamentals"><link rel="next" href="statemgmt.html" title="Chapter&nbsp;3.&nbsp;HTTP state management"></head><body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"><div xmlns:fo="http://www.w3.org/1999/XSL/Format" class="banner"><a class="bannerLeft" href="http://www.apache.org/" title="Apache Software Foundation"><img style="border:none;" src="images/asf_logo_wide.gif"></a><a class="bannerRight" href="http://hc.apache.org/httpcomponents-core/" title="Apache HttpComponents Core"><img style="border:none;" src="images/hc_logo.png"></a><div class="clear"></div></div><div class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="3" align="center">Chapter&nbsp;2.&nbsp;Connection management</th></tr><tr><td width="20%" align="left"><a accesskey="p" href="fundamentals.html">Prev</a>&nbsp;</td><th width="60%" align="center">&nbsp;</th><td width="20%" align="right">&nbsp;<a accesskey="n" href="statemgmt.html">Next</a></td></tr></table><hr></div><div class="chapter" lang="en"><div class="titlepage"><div><div><h2 class="title"><a name="connmgmt"></a>Chapter&nbsp;2.&nbsp;Connection management</h2></div></div></div>
<p>HttpClient has a complete control over the process of connection initialization and
termination as well as I/O operations on active connections. However various aspects of
connection operations can be controlled using a number of parameters.</p>
<div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="d4e391"></a>2.1.&nbsp;Connection parameters</h2></div></div></div>
<p>These are parameters that can influence connection operations:</p>
<div class="itemizedlist"><ul type="disc"><li>
<p>
<b>'http.socket.timeout':&nbsp;</b>
defines the socket timeout (<code class="literal">SO_TIMEOUT</code>) in
milliseconds, which is the timeout for waiting for data or, put differently,
a maximum period inactivity between two consecutive data packets). A timeout
value of zero is interpreted as an infinite timeout. This parameter expects
a value of type <code class="classname">java.lang.Integer</code>. If this parameter
is not set read operations will not time out (infinite timeout).
</p>
<p>
<b>'http.tcp.nodelay':&nbsp;</b>
determines whether Nagle's algorithm is to be used. The Nagle's algorithm
tries to conserve bandwidth by minimizing the number of segments that are
sent. When applications wish to decrease network latency and increase
performance, they can disable Nagle's algorithm (that is enable
<code class="literal">TCP_NODELAY</code>. Data will be sent earlier, at the cost
of an increase in bandwidth consumption. This parameter expects a value of
type <code class="classname">java.lang.Boolean</code>. If this parameter is not,
<code class="literal">TCP_NODELAY</code> will be enabled (no delay).
</p>
<p>
<b>'http.socket.buffer-size':&nbsp;</b>
determines the size of the internal socket buffer used to buffer data
while receiving / transmitting HTTP messages. This parameter expects a value
of type <code class="classname">java.lang.Integer</code>. If this parameter is not
set HttpClient will allocate 8192 byte socket buffers.
</p>
<p>
<b>'http.socket.linger':&nbsp;</b>
sets <code class="literal">SO_LINGER</code> with the specified linger time in
seconds. The maximum timeout value is platform specific. Value 0 implies
that the option is disabled. Value -1 implies that the JRE default is used.
The setting only affects the socket close operation. If this parameter is
not set value -1 (JRE default) will be assumed.
</p>
<p>
<b>'http.connection.timeout':&nbsp;</b>
determines the timeout in milliseconds until a connection is established.
A timeout value of zero is interpreted as an infinite timeout. This
parameter expects a value of type <code class="classname">java.lang.Integer</code>.
If this parameter is not set connect operations will not time out (infinite
timeout).
</p>
<p>
<b>'http.connection.stalecheck':&nbsp;</b>
determines whether stale connection check is to be used. Disabling stale
connection check may result in a noticeable performance improvement (the
check can cause up to 30 millisecond overhead per request) at the risk of
getting an I/O error when executing a request over a connection that has
been closed at the server side. This parameter expects a value of type
<code class="classname">java.lang.Boolean</code>. For performance critical
operations the check should be disabled. If this parameter is not set the
stale connection will be performed before each request execution.
</p>
<p>
<b>'http.connection.max-line-length':&nbsp;</b>
determines the maximum line length limit. If set to a positive value, any
HTTP line exceeding this limit will cause an
<code class="exceptionname">java.io.IOException</code>. A negative or zero
value will effectively disable the check. This parameter expects a value of
type <code class="classname">java.lang.Integer</code>. If this parameter is not set,
no limit will be enforced.
</p>
<p>
<b>'http.connection.max-header-count':&nbsp;</b>
determines the maximum HTTP header count allowed. If set to a positive
value, the number of HTTP headers received from the data stream exceeding
this limit will cause an <code class="exceptionname">java.io.IOException</code>.
A negative or zero value will effectively disable the check. This parameter
expects a value of type <code class="classname">java.lang.Integer</code>. If this
parameter is not set, no limit will be enforced.
</p>
<p>
<b>'http.connection.max-status-line-garbage':&nbsp;</b>
defines the maximum number of ignorable lines before we expect a HTTP
response's status line. With HTTP/1.1 persistent connections, the problem
arises that broken scripts could return a wrong
<code class="literal">Content-Length</code> (there are more bytes sent than
specified). Unfortunately, in some cases, this cannot be detected after the
bad response, but only before the next one. So HttpClient must be able to
skip those surplus lines this way. This parameter expects a value of type
java.lang.Integer. 0 disallows all garbage/empty lines before the status
line. Use <code class="constant">java.lang.Integer#MAX_VALUE</code> for unlimited
number. If this parameter is not set unlimited number will be
assumed.
</p>
</li></ul></div>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="d4e438"></a>2.2.&nbsp;Connection persistence</h2></div></div></div>
<p>The process of establishing a connection from one host to another is quite complex and
involves multiple packet exchanges between two endpoints, which can be quite time
consuming. The overhead of connection handshaking can be significant, especially for
small HTTP messages. One can achieve a much higher data throughput if open connections
can be re-used to execute multiple requests.</p>
<p>HTTP/1.1 states that HTTP connections can be re-used for multiple requests per
default. HTTP/1.0 compliant endpoints can also use similar mechanism to explicitly
communicate their preference to keep connection alive and use it for multiple requests.
HTTP agents can also keep idle connections alive for a certain period time in case a
connection to the same target host may be needed for subsequent requests. The ability to
keep connections alive is usually refered to as connection persistence. HttpClient fully
supports connection persistence.</p>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="d4e442"></a>2.3.&nbsp;HTTP connection routing</h2></div></div></div>
<p>HttpClient is capable of establishing connections to the target host either directly
or via a route that may involve multiple intermediate connections also referred to as
hops. HttpClient differentiates connections of a route into plain, tunneled and layered.
The use of multiple intermediate proxies to tunnel connections to the target host is
referred to as proxy chaining.</p>
<p>Plain routes are established by connecting to the target or the first and only proxy.
Tunnelled routes are established by connecting to the first and tunnelling through a
chain of proxies to the target. Routes without a proxy cannot be tunnelled. Layered
routes are established by layering a protocol over an existing connection. Protocols can
only be layered over a tunnel to the target, or over a direct connection without
proxies.</p>
<div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="d4e446"></a>2.3.1.&nbsp;Route computation</h3></div></div></div>
<p><code class="interfacename">RouteInfo</code> interface represents information about a
definitive route to a target host involving one or more intermediate steps or hops.
<code class="classname">HttpRoute</code> is a concrete implementation of
<code class="interfacename">RouteInfo</code>, which cannot be changed (is
immutable). <code class="classname">HttpTracker</code> is a mutable
<code class="interfacename">RouteInfo</code> implementation used internally by
HttpClient to track the remaining hops to the ultimate route target.
<code class="classname">HttpTracker</code> can be updated after a successful execution
of the next hop towards the route target. <code class="classname">HttpRouteDirector</code>
is a helper class that can be used to compute the next step in a route. This class
is used internally by HttpClient.</p>
<p><code class="interfacename">HttpRoutePlanner</code> is an interface representing a
strategy to compute a complete route to a given target based on the execution
context. HttpClient ships with two default
<code class="interfacename">HttpRoutePlanner</code> implementation.
<code class="classname">ProxySelectorRoutePlanner</code> is based on
<code class="classname">java.net.ProxySelector</code>. By default, it will pick up the
proxy settings of the JVM, either from system properties or from the browser running
the application. <code class="classname">DefaultHttpRoutePlanner</code> implementation does
not make use of any Java system properties, nor of system or browser proxy settings.
It computes routes based exclusively on HTTP parameters described below.</p>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="d4e462"></a>2.3.2.&nbsp;Secure HTTP connections</h3></div></div></div>
<p>HTTP connections can be considered secure if information transmitted between two
connection endpoints cannot be read or tampered with by an unauthorized third party.
The SSL/TLS protocol is the most widely used technique to ensure HTTP transport
security. However, other encryption techniques could be employed as well. Usually,
HTTP transport is layered over the SSL/TLS encrypted connection.</p>
</div>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="d4e465"></a>2.4.&nbsp;HTTP route parameters</h2></div></div></div>
<p>These are parameters that can influence route computation:</p>
<div class="itemizedlist"><ul type="disc"><li>
<p>
<b>'http.route.default-proxy':&nbsp;</b>
defines a proxy host to be used by default route planners that do not make
use of JRE settings. This parameter expects a value of type
<code class="classname">HttpHost</code>. If this parameter is not set direct
connections to the target will be attempted.
</p>
</li><li>
<p>
<b>'http.route.local-address':&nbsp;</b>
defines a local address to be used by all default route planner. On
machines with multiple network interfaces, this parameter can be used to
select the network interface from which the connection originates. This
parameter expects a value of type
<code class="classname">java.net.InetAddress</code>. If this parameter is not
set a default local address will be used automatically.
</p>
</li><li>
<p>
<b>'http.route.forced-route':&nbsp;</b>
defines an forced route to be used by all default route planner. Instead
of computing a route, the given forced route will be returned, even if it
points to a completely different target host. This parameter expects a value
of type <code class="classname">HttpRoute</code>.
</p>
</li></ul></div>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="d4e484"></a>2.5.&nbsp;Socket factories</h2></div></div></div>
<p>HTTP connections make use of a <code class="classname">java.net.Socket</code> object
internally to handle transmission of data across the wire. They, however, rely on
<code class="interfacename">SocketFactory</code> interface to create, initialize and
connect sockets. This enables the users of HttpClient to provide application specific
socket initialization code at runtime. <code class="classname">PlainSocketFactory</code> is the
default factory for creating and initializing plain (unencrypted) sockets.</p>
<p>The process of creating a socket and that of connecting it to a host are decoupled, so
that the socket could be closed while being blocked in the connect operation.</p>
<pre class="programlisting">
PlainSocketFactory sf = PlainSocketFactory.getSocketFactory();
Socket socket = sf.createSocket();
 
HttpParams params = new BasicHttpParams();
params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000L);
sf.connectSocket(socket, "locahost", 8080, null, -1, params);
</pre>
<div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="d4e492"></a>2.5.1.&nbsp;Secure socket layering</h3></div></div></div>
<p><code class="interfacename">LayeredSocketFactory</code> is an extension of
<code class="interfacename">SocketFactory</code> interface. Layered socket factories
are capable of creating sockets that are layered over an existing plain socket.
Socket layering is used primarily for creating secure sockets through proxies.
HttpClient ships with SSLSocketFactory that implements SSL/TLS layering. Please note
HttpClient does not use any custom encryption functionality. It is fully reliant on
standard Java Cryptography (JCE) and Secure Sockets (JSEE) extensions.</p>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="d4e497"></a>2.5.2.&nbsp;SSL/TLS customization</h3></div></div></div>
<p>HttpClient makes use of SSLSocketFactory to create SSL connections.
<code class="classname">SSLSocketFactory</code> allows for a high degree of
customization. It can take an instance of
<code class="interfacename">javax.net.ssl.SSLContext</code> as a parameter and use
it to create custom configured SSL connections.</p>
<pre class="programlisting">
TrustManager easyTrustManager = new X509TrustManager() {
 
@Override
public void checkClientTrusted(
X509Certificate[] chain,
String authType) throws CertificateException {
// Oh, I am easy!
}
 
@Override
public void checkServerTrusted(
X509Certificate[] chain,
String authType) throws CertificateException {
// Oh, I am easy!
}
 
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
 
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null, new TrustManager[] { easyTrustManager }, null);
 
SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
SSLSocket socket = (SSLSocket) sf.createSocket();
socket.setEnabledCipherSuites(new String[] { "SSL_RSA_WITH_RC4_128_MD5" });
 
HttpParams params = new BasicHttpParams();
params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000L);
sf.connectSocket(socket, "locahost", 443, null, -1, params);
</pre>
<p>Customization of SSLSocketFactory implies a certain degree of familiarity with the
concepts of the SSL/TLS protocol, a detailed explanation of which is out of scope
for this document. Please refer to the <a class="ulink" href="http://java.sun.com/j2se/1.5.0/docs/guide/security/jsse/JSSERefGuide.html" target="_top">Java Secure Socket Extension</a> for a detailed description of
<code class="interfacename">javax.net.ssl.SSLContext</code> and related
tools.</p>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="d4e506"></a>2.5.3.&nbsp;Hostname verification</h3></div></div></div>
<p>In addition to the trust verification and the client authentication performed on
the SSL/TLS protocol level, HttpClient can optionally verify whether the target
hostname matches the names stored inside the server's X.509 certificate, once the
connection has been established. This verification can provide additional guarantees
of authenticity of the server trust material. X509HostnameVerifier interface
represents a strategy for hostname verification. HttpClient ships with three
X509HostnameVerifier. Important: hostname verification should not be confused with
SSL trust verification.</p>
<div class="itemizedlist"><ul type="disc"><li>
<p>
<b><code class="classname">StrictHostnameVerifier</code>:&nbsp;</b>
The strict hostname verifier works the same way as Sun Java 1.4, Sun
Java 5, Sun Java 6. It's also pretty close to IE6. This implementation
appears to be compliant with RFC 2818 for dealing with wildcards. The
hostname must match either the first CN, or any of the subject-alts. A
wildcard can occur in the CN, and in any of the subject-alts.
</p>
</li><li>
<p>
<b><code class="classname">BrowserCompatHostnameVerifier</code>:&nbsp;</b>
The hostname verifier that works the same way as Curl and Firefox. The
hostname must match either the first CN, or any of the subject-alts. A
wildcard can occur in the CN, and in any of the subject-alts. The only
difference between <code class="classname">BrowserCompatHostnameVerifier</code>
and <code class="classname">StrictHostnameVerifier</code> is that a wildcard
(such as "*.foo.com") with
<code class="classname">BrowserCompatHostnameVerifier</code> matches all
subdomains, including "a.b.foo.com".
</p>
</li><li>
<p>
<b><code class="classname">AllowAllHostnameVerifier</code>:&nbsp;</b>
This hostname verifier essentially turns hostname verification off.
This implementation is a no-op, and never throws the
<code class="exceptionname">javax.net.ssl.SSLException</code>.
</p>
</li></ul></div>
<p>Per default HttpClient uses <code class="classname">BrowserCompatHostnameVerifier</code>
implementation. One can specify a different hostname verifier implementation if
desired</p>
<pre class="programlisting">
SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getInstance("TLS"));
sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
</pre>
</div>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="d4e532"></a>2.6.&nbsp;Protocol schemes</h2></div></div></div>
<p><code class="classname">Scheme</code> class represents a protocol scheme such as "http" or
"https" and contains a number of protocol properties such as the default port and the
socket factory to be used to creating <code class="classname">java.net.Socket</code> instances
for the given protocol. <code class="classname">SchemeRegistry</code> class is used to maintain
a set of <code class="classname">Scheme</code>s HttpClient can choose from when trying to
establish a connection by a request URI:</p>
<pre class="programlisting">
Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);
 
SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getInstance("TLS"));
sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
Scheme https = new Scheme("https", sf, 443);
 
SchemeRegistry sr = new SchemeRegistry();
sr.register(http);
sr.register(https);
</pre>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="d4e540"></a>2.7.&nbsp;HttpClient proxy configuration</h2></div></div></div>
<p>Even though HttpClient is aware of complex routing scemes and proxy chaining, it
supports only simple direct or one hop proxy connections out of the box.</p>
<p>The simplest way to tell HttpClient to connect to the target host via a proxy is by
setting the default proxy parameter:</p>
<pre class="programlisting">
DefaultHttpClient httpclient = new DefaultHttpClient();
 
HttpHost proxy = new HttpHost("someproxy", 8080);
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
</pre>
<p>One can also instruct HttpClient to use standard JRE proxy selector to obtain proxy
information:</p>
<pre class="programlisting">
DefaultHttpClient httpclient = new DefaultHttpClient();
 
ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
httpclient.getConnectionManager().getSchemeRegistry(),
ProxySelector.getDefault());
httpclient.setRoutePlanner(routePlanner);
</pre>
<p>Alternatively, one can provide a custom <code class="interfacename">RoutePlanner</code>
implementation in order to have a complete control over the process of HTTP route
computation:</p>
<pre class="programlisting">
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.setRoutePlanner(new HttpRoutePlanner() {
 
public HttpRoute determineRoute(
HttpHost target,
HttpRequest request,
HttpContext context) throws HttpException {
return new HttpRoute(target, null, new HttpHost("someproxy", 8080),
"https".equalsIgnoreCase(target.getSchemeName()));
}
});
</pre>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="d4e550"></a>2.8.&nbsp;HTTP connection managers</h2></div></div></div>
<div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="d4e552"></a>2.8.1.&nbsp;Connection operators</h3></div></div></div>
<p>Operated connections are client side connections whose underlying socket or its
state can be manipulated by an external entity, usually referred to as a connection
operator. <code class="interfacename">OperatedClientConnection</code> interface extends
<code class="interfacename">HttpClientConnection</code> interface and define
additional methods to manage connection socket. The
<code class="interfacename">ClientConnectionOperator</code> interface represents a
strategy for creating <code class="interfacename">OperatedClientConnection</code>
instances and updating the underlying socket of those objects. Implementations will
most likely make use <code class="interfacename">SocketFactory</code>s to create
<code class="classname">java.net.Socket</code> instances. The
<code class="interfacename">ClientConnectionOperator</code> interface enables the
users of HttpClient to provide a custom strategy for connection operators as well as
an ability to provide alternative implementation of the
<code class="interfacename">OperatedClientConnection</code> interface.</p>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="d4e563"></a>2.8.2.&nbsp;Managed connections and connection managers</h3></div></div></div>
<p>HTTP connections are complex, stateful, thread-unsafe objects which need to be
properly managed to function correctly. HTTP connections can only be used by one
execution thread at a time. HttpClient employs a special entity to manage access to
HTTP connections called HTTP connection manager and represented by the
<code class="interfacename">ClientConnectionManager</code> interface. The purpose of
an HTTP connection manager is to serve as a factory for new HTTP connections, manage
persistent connections and synchronize access to persistent connections making sure
that only one thread can have access to a connection at a time.</p>
<p>Internally HTTP connection managers work with instances of
<code class="interfacename">OperatedClientConnection</code>, but they hands out
instances of <code class="interfacename">ManagedClientConnection</code> to the service
consumers. <code class="interfacename">ManagedClientConnection</code> acts as a wrapper
for a <code class="interfacename">OperatedClientConnection</code> instance that manages
its state and controls all I/O operations on that connection. It also abstracts away
socket operations and provides convenience methods for opening and updating sockets
in order to establish a route.
<code class="interfacename">ManagedClientConnection</code> instances are aware of
their link to the connection manager that spawned them and of the fact that they
must be returned back to the manager when no longer in use.
<code class="interfacename">ManagedClientConnection</code> classes also implement
<code class="interfacename">ConnectionReleaseTrigger</code> interface that can be
used to trigger the release of the connection back to the manager. Once the
connection release has been triggered the wrapped connection gets detached from the
<code class="interfacename">ManagedClientConnection</code> wrapper and the
<code class="interfacename">OperatedClientConnection</code> instance is returned
back to the manager. Even though the service consumer still holds a reference to the
<code class="interfacename">ManagedClientConnection</code> instance, it is no longer
able to execute any I/O operation or change the state of the
<code class="interfacename">OperatedClientConnection</code> either intentionally or
unintentionally.</p>
<p>This is an example of acquiring a connection from a connection manager:</p>
<pre class="programlisting">
HttpParams params = new BasicHttpParams();
Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);
SchemeRegistry sr = new SchemeRegistry();
sr.register(http);
 
ClientConnectionManager connMrg = new SingleClientConnManager(params, sr);
 
// Request new connection. This can be a long process
ClientConnectionRequest connRequest = connMrg.requestConnection(
new HttpRoute(new HttpHost("localhost", 80)), null);
 
// Wait for connection up to 10 sec
ManagedClientConnection conn = connRequest.getConnection(10, TimeUnit.SECONDS);
try {
// Do useful things with the connection.
// Release it when done.
conn.releaseConnection();
} catch (IOException ex) {
// Abort connection upon an I/O error.
conn.abortConnection();
throw ex;
}
</pre>
<p>The connection request can be terminated prematurely by calling
<code class="methodname">ClientConnectionRequest#abortRequest()</code> if necessary.
This will unblock the thread blocked in the
<code class="methodname">ClientConnectionRequest#getConnection()</code> method.</p>
<p><code class="classname">BasicManagedEntity</code> wrapper class can be used to ensure
automatic release of the underlying connection once the response content has been
fully consumed. HttpClient uses this mechanism internally to achieve transparent
connection release for all responses obtained from
<code class="methodname">HttpClient#execute()</code> methods:</p>
<pre class="programlisting">
ClientConnectionRequest connRequest = connMrg.requestConnection(
new HttpRoute(new HttpHost("localhost", 80)), null);
ManagedClientConnection conn = connRequest.getConnection(10, TimeUnit.SECONDS);
try {
BasicHttpRequest request = new BasicHttpRequest("GET", "/");
conn.sendRequestHeader(request);
HttpResponse response = conn.receiveResponseHeader();
conn.receiveResponseEntity(response);
HttpEntity entity = response.getEntity();
if (entity != null) {
BasicManagedEntity managedEntity = new BasicManagedEntity(entity, conn, true);
// Replace entity
response.setEntity(managedEntity);
}
// Do something useful with the response
// The connection will be released automatically
// as soon as the response content has been consumed
} catch (IOException ex) {
// Abort connection upon an I/O error.
conn.abortConnection();
throw ex;
}
</pre>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="d4e588"></a>2.8.3.&nbsp;Simple connection manager</h3></div></div></div>
<p><code class="classname">SingleClientConnManager</code> is a simple connection manager that
maintains only one connection at a time. Even though this class is thread-safe it
ought to be used by one execution thread only.
<code class="classname">SingleClientConnManager</code> will make an effort to reuse the
connection for subsequent requests with the same route. It will, however, close the
existing connection and open it for the given route, if the route of the persistent
connection does not match that of the connection request. If the connection has been
already been allocated
<code class="exceptionname">java.lang.IllegalStateException</code> is thrown.</p>
<p><code class="classname">SingleClientConnManager</code> is used by HttpClient per
default.</p>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="d4e596"></a>2.8.4.&nbsp;Pooling connection manager</h3></div></div></div>
<p><code class="classname">ThreadSafeClientConnManager</code> is a more complex
implementation that manages a pool of client connections and is able to service
connection requests from multiple execution threads. Connections are pooled on a per
route basis. A request for a route which already the manager has persistent
connections for available in the pool will be services by leasing a connection from
the pool rather than creating a brand new connection.</p>
<p><code class="classname">ThreadSafeClientConnManager</code> maintains a maximum limit of
connection on a per route basis and in total. Per default this implementation will
create no more than than 2 concurrent connections per given route and no more 20
connections in total. For many real-world applications these limits may prove too
constraining, especially if they use HTTP as a transport protocol for their
services. Connection limits, however, can be adjusted using HTTP parameters.</p>
<p>This example shows how the connection pool parameters can be adjusted:</p>
<pre class="programlisting">
HttpParams params = new BasicHttpParams();
// Increase max total connection to 200
ConnManagerParams.setMaxTotalConnections(params, 200);
// Increase default max connection per route to 20
ConnPerRouteBean connPerRoute = new ConnPerRouteBean(20);
// Increase max connections for localhost:80 to 50
HttpHost localhost = new HttpHost("locahost", 80);
connPerRoute.setMaxForRoute(new HttpRoute(localhost), 50);
ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);
 
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(
new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
schemeRegistry.register(
new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
 
ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
HttpClient httpClient = new DefaultHttpClient(cm, params);
</pre>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="d4e604"></a>2.8.5.&nbsp;Connection manager shutdown</h3></div></div></div>
<p>When an HttpClient instance is no longer needed and is about to go out of scope it
is important to shut down its connection manager to ensure that all connections kept
alive by the manager get closed and system resources allocated by those connections
are released.</p>
<pre class="programlisting">
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://www.google.com/");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println(response.getStatusLine());
if (entity != null) {
entity.consumeContent();
}
httpclient.getConnectionManager().shutdown();
</pre>
</div>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="d4e608"></a>2.9.&nbsp;Connection management parameters</h2></div></div></div>
<p>These are parameters that be used to customize standard HTTP connection manager
implementations:</p>
<div class="itemizedlist"><ul type="disc"><li>
<p>
<b>'http.conn-manager.timeout':&nbsp;</b>
defines the timeout in milliseconds used when retrieving an instance of
<code class="interfacename">ManagedClientConnection</code> from the
<code class="interfacename">ClientConnectionManager</code> This parameter
expects a value of type <code class="classname">java.lang.Long</code>. If this
parameter is not set connection requests will not time out (infinite
timeout).
</p>
</li><li>
<p>
<b>'http.conn-manager.max-per-route':&nbsp;</b>
defines the maximum number of connections per route. This limit is
interpreted by client connection managers and applies to individual manager
instances. This parameter expects a value of type
<code class="interfacename">ConnPerRoute</code>.
</p>
</li><li>
<p>
<b>'http.conn-manager.max-total':&nbsp;</b>
defines the maximum number of connections in total. This limit is
interpreted by client connection managers and applies to individual manager
instances. This parameter expects a value of type
<code class="classname">java.lang.Integer</code>.
</p>
</li></ul></div>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="d4e629"></a>2.10.&nbsp;Multithreaded request execution</h2></div></div></div>
<p>When equipped with a pooling connection manager such as ThreadSafeClientConnManager
HttpClient can be used to execute multiple requests simultaneously using multiple
threads of execution.</p>
<p><code class="classname">ThreadSafeClientConnManager</code> will allocate connections based on
its configuration. If all connections for a given route have already been leased, a
request for connection will block until a connection is released back to the pool. One
can ensure the connection manager does not block indefinitely in the connection request
operation by setting <code class="literal">'http.conn-manager.timeout'</code> to a positive value.
If the connection request cannot be serviced within the given time period
<code class="exceptionname">ConnectionPoolTimeoutException</code> will be thrown.</p>
<pre class="programlisting">
HttpParams params = new BasicHttpParams();
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(
new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
 
ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
HttpClient httpClient = new DefaultHttpClient(cm, params);
 
// URIs to perform GETs on
String[] urisToGet = {
"http://www.domain1.com/",
"http://www.domain2.com/",
"http://www.domain3.com/",
"http://www.domain4.com/"
};
 
// create a thread for each URI
GetThread[] threads = new GetThread[urisToGet.length];
for (int i = 0; i &lt; threads.length; i++) {
HttpGet httpget = new HttpGet(urisToGet[i]);
threads[i] = new GetThread(httpClient, httpget);
}
 
// start the threads
for (int j = 0; j &lt; threads.length; j++) {
threads[j].start();
}
 
// join the threads
for (int j = 0; j &lt; threads.length; j++) {
threads[j].join();
}
 
</pre>
<pre class="programlisting">
static class GetThread extends Thread {
private final HttpClient httpClient;
private final HttpContext context;
private final HttpGet httpget;
public GetThread(HttpClient httpClient, HttpGet httpget) {
this.httpClient = httpClient;
this.context = new BasicHttpContext();
this.httpget = httpget;
}
@Override
public void run() {
try {
HttpResponse response = this.httpClient.execute(this.httpget, this.context);
HttpEntity entity = response.getEntity();
if (entity != null) {
// do something useful with the entity
// ...
// ensure the connection gets released to the manager
entity.consumeContent();
}
} catch (Exception ex) {
this.httpget.abort();
}
}
}
</pre>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="d4e638"></a>2.11.&nbsp;Connection eviction policy</h2></div></div></div>
<p>One of the major shortcoming of the classic blocking I/O model is that the network
socket can react to I/O events only when blocked in an I/O operation. When a connection
is released back to the manager, it can be kept alive however it is unable to monitor
the status of the socket and react to any I/O events. If the connection gets closed on
the server side, the client side connection is unable to detect the change in the
connection state and react appropriately by closing the socket on its end.</p>
<p>HttpClient tries to mitigate the problem by testing whether the connection is 'stale',
that is no longer valid because it was closed on the server side, prior to using the
connection for executing an HTTP request. The stale connection check is not 100%
reliable and adds 10 to 30 ms overhead to each request execution. The only feasible
solution that does not involve a one thread per socket model for idle connections is a
dedicated monitor thread used to evict connections that are considered expired due to a
long period of inactivity. The monitor thread can periodically call
<code class="methodname">ClientConnectionManager#closeExpiredConnections()</code> method to
close all expired connections and evict closed connections from the pool. It can also
optionally call <code class="methodname">ClientConnectionManager#closeIdleConnections()</code>
method to close all connections that have been idle over a given period of time.</p>
<pre class="programlisting">
public static class IdleConnectionMonitorThread extends Thread {
private final ClientConnectionManager connMgr;
private volatile boolean shutdown;
public IdleConnectionMonitorThread(ClientConnectionManager connMgr) {
super();
this.connMgr = connMgr;
}
 
@Override
public void run() {
try {
while (!shutdown) {
synchronized (this) {
wait(5000);
// Close expired connections
connMgr.closeExpiredConnections();
// Optionally, close connections
// that have been idle longer than 30 sec
connMgr.closeIdleConnections(30, TimeUnit.SECONDS);
}
}
} catch (InterruptedException ex) {
// terminate
}
}
public void shutdown() {
shutdown = true;
synchronized (this) {
notifyAll();
}
}
}
</pre>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="d4e645"></a>2.12.&nbsp;Connection keep alive strategy</h2></div></div></div>
<p>The HTTP specification does not specify how long a persistent connection may be and
should be kept alive. Some HTTP servers use non-standard <code class="literal">Keep-Alive</code>
header to communicate to the client the period of time in seconds they intend to keep
the connection alive on the server side. HttpClient makes use of this information if
available. If the <code class="literal">Keep-Alive</code> header is not present in the response,
HttpClient assumes the connection can be kept alive indefinitely. However, many HTTP
servers out there are configured to drop persistent connections after a certain period
of inactivity in order to conserve system resources, quite often without informing the
client. In case the default strategy turns out to be too optimistic, one may want to
provide a custom keep-alive strategy.</p>
<pre class="programlisting">
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {
 
public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
// Honor 'keep-alive' header
HeaderElementIterator it = new BasicHeaderElementIterator(
response.headerIterator(HTTP.CONN_KEEP_ALIVE));
while (it.hasNext()) {
HeaderElement he = it.nextElement();
String param = he.getName();
String value = he.getValue();
if (value != null &amp;&amp; param.equalsIgnoreCase("timeout")) {
try {
return Long.parseLong(value) * 1000;
} catch(NumberFormatException ignore) {
}
}
}
HttpHost target = (HttpHost) context.getAttribute(
ExecutionContext.HTTP_TARGET_HOST);
if ("www.naughty-server.com".equalsIgnoreCase(target.getHostName())) {
// Keep alive for 5 seconds only
return 5 * 1000;
} else {
// otherwise keep alive for 30 seconds
return 30 * 1000;
}
}
});
</pre>
</div>
</div><div class="navfooter"><hr><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="fundamentals.html">Prev</a>&nbsp;</td><td width="20%" align="center">&nbsp;</td><td width="40%" align="right">&nbsp;<a accesskey="n" href="statemgmt.html">Next</a></td></tr><tr><td width="40%" align="left" valign="top">Chapter&nbsp;1.&nbsp;Fundamentals&nbsp;</td><td width="20%" align="center"><a accesskey="h" href="index.html">Home</a></td><td width="40%" align="right" valign="top">&nbsp;Chapter&nbsp;3.&nbsp;HTTP state management</td></tr></table></div></body></html>
/ViaThinkSoft Java Utils/lib/httpcomponents-client-4.0.1/tutorial/html/css/hc-tutorial.css
0,0 → 1,309
/*
====================================================================
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
 
http://www.apache.org/licenses/LICENSE-2.0
 
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
====================================================================
 
This software consists of voluntary contributions made by many
individuals on behalf of the Apache Software Foundation. For more
information on the Apache Software Foundation, please see
<http://www.apache.org/>.
====================================================================
Based on the CSS file for the Spring Reference Documentation.
*/
 
 
body {
text-align: justify;
margin-right: 2em;
margin-left: 2em;
}
 
a:active {
color: #003399;
}
 
a:visited {
color: #888888;
}
 
p {
font-family: Verdana, Arial, sans-serif;
}
 
dt {
font-family: Verdana, Arial, sans-serif;
font-size: 12px;
}
 
p, dl, dt, dd, blockquote {
color: #000000;
margin-bottom: 3px;
margin-top: 3px;
padding-top: 0px;
}
 
ol, ul, p {
margin-top: 6px;
margin-bottom: 6px;
}
 
p, blockquote {
font-size: 90%;
}
 
p.releaseinfo {
font-size: 100%;
font-weight: bold;
font-family: Verdana, Arial, helvetica, sans-serif;
padding-top: 10px;
}
 
p.pubdate {
font-size: 120%;
font-weight: bold;
font-family: Verdana, Arial, helvetica, sans-serif;
}
 
td {
font-size: 80%;
}
 
td, th, span {
color: #000000;
}
 
blockquote {
margin-right: 0px;
}
 
h1, h2, h3, h4, h6, H6 {
color: #000000;
font-weight: 500;
margin-top: 0px;
padding-top: 14px;
font-family: Verdana, Arial, helvetica, sans-serif;
margin-bottom: 0px;
}
 
h2.title {
font-weight: 800;
margin-bottom: 8px;
}
 
h2.subtitle {
font-weight: 800;
margin-bottom: 20px;
}
 
.firstname, .surname {
font-size: 12px;
font-family: Verdana, Arial, helvetica, sans-serif;
}
 
table {
border-collapse: collapse;
border-spacing: 0;
border: 1px black;
empty-cells: hide;
margin: 10px 0px 30px 50px;
width: 90%;
}
 
div.table {
margin: 30px 0px 30px 0px;
border: 1px dashed gray;
padding: 10px;
}
 
div .table-contents table {
border: 1px solid black;
}
 
div.table > p.title {
padding-left: 10px;
}
 
td {
padding: 4pt;
font-family: Verdana, Arial, helvetica, sans-serif;
}
 
div.warning TD {
text-align: justify;
}
 
h1 {
font-size: 150%;
}
 
h2 {
font-size: 110%;
}
 
h3 {
font-size: 100%;
font-weight: bold;
}
 
h4 {
font-size: 90%;
font-weight: bold;
}
 
h5 {
font-size: 90%;
font-style: italic;
}
 
h6 {
font-size: 100%;
font-style: italic;
}
 
tt {
font-size: 110%;
font-family: "Courier New", Courier, monospace;
color: #000000;
}
 
.navheader, .navfooter {
border: none;
}
 
pre {
font-size: 110%;
padding: 5px;
border-style: solid;
border-width: 1px;
border-color: #CCCCCC;
background-color: #f3f5e9;
}
 
ul, ol, li {
list-style: disc;
}
 
hr {
width: 100%;
height: 1px;
background-color: #CCCCCC;
border-width: 0px;
padding: 0px;
}
 
.variablelist {
padding-top: 10px;
padding-bottom: 10px;
margin: 0;
}
 
.term {
font-weight: bold;
}
 
.mediaobject {
padding-top: 30px;
padding-bottom: 30px;
}
 
.legalnotice {
font-family: Verdana, Arial, helvetica, sans-serif;
font-size: 12px;
font-style: italic;
}
 
.sidebar {
float: right;
margin: 10px 0px 10px 30px;
padding: 10px 20px 20px 20px;
width: 33%;
border: 1px solid black;
background-color: #F4F4F4;
font-size: 14px;
}
 
.property {
font-family: "Courier New", Courier, monospace;
}
 
a code {
font-family: Verdana, Arial, monospace;
font-size: 12px;
}
 
td code {
font-size: 110%;
}
 
div.note * td,
div.tip * td,
div.warning * td,
div.calloutlist * td {
text-align: justify;
font-size: 100%;
}
 
.programlisting .interfacename,
.programlisting .literal,
.programlisting .classname {
font-size: 95%;
}
 
.title .interfacename,
.title .literal,
.title .classname {
font-size: 130%;
}
 
.programlisting * .lineannotation,
.programlisting * .lineannotation * {
color: blue;
}
 
.bannerLeft, .bannerRight {
font-size: xx-large;
font-weight: bold;
}
 
.bannerLeft img, .bannerRight img {
margin: 0px;
}
 
.bannerLeft img {
float:left;
text-shadow: #7CFC00;
}
 
.bannerRight img {
float:right;
text-shadow: #7CFC00;
}
 
.banner {
padding: 0px;
}
 
.banner img {
border: none;
}
 
.clear {
clear:both;
visibility: hidden;
}
/ViaThinkSoft Java Utils/lib/httpcomponents-client-4.0.1/tutorial/html/advanced.html
0,0 → 1,195
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Chapter&nbsp;6.&nbsp;Advanced topics</title><link rel="stylesheet" href="css/hc-tutorial.css" type="text/css"><meta name="generator" content="DocBook XSL-NS Stylesheets V1.73.2"><link rel="start" href="index.html" title="HttpClient Tutorial"><link rel="up" href="index.html" title="HttpClient Tutorial"><link rel="prev" href="httpagent.html" title="Chapter&nbsp;5.&nbsp;HTTP client service"></head><body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"><div xmlns:fo="http://www.w3.org/1999/XSL/Format" class="banner"><a class="bannerLeft" href="http://www.apache.org/" title="Apache Software Foundation"><img style="border:none;" src="images/asf_logo_wide.gif"></a><a class="bannerRight" href="http://hc.apache.org/httpcomponents-core/" title="Apache HttpComponents Core"><img style="border:none;" src="images/hc_logo.png"></a><div class="clear"></div></div><div class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="3" align="center">Chapter&nbsp;6.&nbsp;Advanced topics</th></tr><tr><td width="20%" align="left"><a accesskey="p" href="httpagent.html">Prev</a>&nbsp;</td><th width="60%" align="center">&nbsp;</th><td width="20%" align="right">&nbsp;</td></tr></table><hr></div><div class="chapter" lang="en"><div class="titlepage"><div><div><h2 class="title"><a name="advanced"></a>Chapter&nbsp;6.&nbsp;Advanced topics</h2></div></div></div>
<div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="d4e1063"></a>6.1.&nbsp;Custom client connections</h2></div></div></div>
<p>In certain situations it may be necessary to customize the way HTTP messages get
transmitted across the wire beyond what is possible possible using HTTP parameters in
order to be able to deal non-standard, non-compliant behaviours. For instance, for web
crawlers it may be necessary to force HttpClient into accepting malformed response heads
in order to salvage the content of the messages. </p>
<p>Usually the process of plugging in a custom message parser or a custom connection
implementation involves several steps:</p>
<div class="itemizedlist"><ul type="disc"><li>
<p>Provide a custom <code class="interfacename">LineParser</code> /
<code class="interfacename">LineFormatter</code> interface implementation.
Implement message parsing / formatting logic as required.</p>
<pre class="programlisting">
class MyLineParser extends BasicLineParser {
 
@Override
public Header parseHeader(
final CharArrayBuffer buffer) throws ParseException {
try {
return super.parseHeader(buffer);
} catch (ParseException ex) {
// Suppress ParseException exception
return new BasicHeader("invalid", buffer.toString());
}
}
}
</pre>
</li><li>
<p>Provide a custom <code class="interfacename">OperatedClientConnection</code>
implementation. Replace default request / response parsers, request / response
formatters with custom ones as required. Implement different message writing /
reading code if necessary.</p>
<pre class="programlisting">
class MyClientConnection extends DefaultClientConnection {
 
@Override
protected HttpMessageParser createResponseParser(
final SessionInputBuffer buffer,
final HttpResponseFactory responseFactory,
final HttpParams params) {
return new DefaultResponseParser(
buffer,
new MyLineParser(),
responseFactory,
params);
}
}
</pre>
</li><li>
<p>Provide a custom <code class="interfacename">ClientConnectionOperator</code>
interface implementation in order to create connections of new class. Implement
different socket initialization code if necessary.</p>
<pre class="programlisting">
class MyClientConnectionOperator extends DefaultClientConnectionOperator {
public MyClientConnectionOperator(final SchemeRegistry sr) {
super(sr);
}
 
@Override
public OperatedClientConnection createConnection() {
return new MyClientConnection();
}
}
</pre>
</li><li>
<p>Provide a custom <code class="interfacename">ClientConnectionManager</code>
interface implementation in order to create connection operator of new
class.</p>
<pre class="programlisting">
class MyClientConnManager extends SingleClientConnManager {
public MyClientConnManager(
final HttpParams params,
final SchemeRegistry sr) {
super(params, sr);
}
 
@Override
protected ClientConnectionOperator createConnectionOperator(
final SchemeRegistry sr) {
return new MyClientConnectionOperator(sr);
}
}
</pre>
</li></ul></div>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="stateful_conn"></a>6.2.&nbsp;Stateful HTTP connections</h2></div></div></div>
<p>While HTTP specification assumes that session state information is always embedded in
HTTP messages in the form of HTTP cookies and therefore HTTP connections are always
stateless, this assumption does not always hold true in real life. There are cases when
HTTP connections are created with a particular user identity or within a particular
security context and therefore cannot be shared with other users and can be reused by
the same user only. Examples of such stateful HTTP connections are
<code class="literal">NTLM</code> authenticated connections and SSL connections with client
certificate authentication.</p>
<div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="d4e1089"></a>6.2.1.&nbsp;User token handler</h3></div></div></div>
<p>HttpClient relies on <code class="interfacename">UserTokenHandler</code> interface to
determine if the given execution context is user specific or not. The token object
returned by this handler is expected to uniquely identify the current user if the
context is user specific or to be null if the context does not contain any resources
or details specific to the current user. The user token will be used to ensure that
user specific resources will not be shared with or reused by other users.</p>
<p>The default implementation of the <code class="interfacename">UserTokenHandler</code>
interface uses an instance of Principal class to represent a state object for HTTP
connections, if it can be obtained from the given execution context.
<code class="classname">DefaultUserTokenHandler</code> will use the user principle of
connection based authentication schemes such as <code class="literal">NTLM</code> or that of
the SSL session with client authentication turned on. If both are unavailable, null
token will be returned.</p>
<p>Users can provide a custom implementation if the default one does not satisfy
their needs:</p>
<pre class="programlisting">
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.setUserTokenHandler(new UserTokenHandler() {
 
public Object getUserToken(HttpContext context) {
return context.getAttribute("my-token");
}
});
</pre>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="d4e1099"></a>6.2.2.&nbsp;User token and execution context</h3></div></div></div>
<p>In the course of HTTP request execution HttpClient adds the following user
identity related objects to the execution context: </p>
<div class="itemizedlist"><ul type="disc"><li>
<p>
<b>'http.user-token':&nbsp;</b>
Object instance representing the actual user identity, usually
expected to be an instance of <code class="interfacename">Principle</code>
interface
</p>
</li></ul></div>
<p>One can find out whether or not the connection used to execute the request was
stateful by examining the content of the local HTTP context after the request has
been executed.</p>
<pre class="programlisting">
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpget = new HttpGet("http://localhost:8080/");
HttpResponse response = httpclient.execute(httpget, localContext);
HttpEntity entity = response.getEntity();
if (entity != null) {
entity.consumeContent();
}
Object userToken = localContext.getAttribute(ClientContext.USER_TOKEN);
System.out.println(userToken);
</pre>
<div class="section" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="d4e1110"></a>6.2.2.1.&nbsp;Persistent stateful connections</h4></div></div></div>
<p>Please note that persistent connection that carry a state object can be reused
only if the same state object is bound to the execution context when requests
are executed. So, it is really important to ensure the either same context is
reused for execution of subsequent HTTP requests by the same user or the user
token is bound to the context prior to request execution.</p>
<pre class="programlisting">
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpContext localContext1 = new BasicHttpContext();
HttpGet httpget1 = new HttpGet("http://localhost:8080/");
HttpResponse response1 = httpclient.execute(httpget1, localContext1);
HttpEntity entity1 = response1.getEntity();
if (entity1 != null) {
entity1.consumeContent();
}
Principal principal = (Principal) localContext1.getAttribute(
ClientContext.USER_TOKEN);
 
HttpContext localContext2 = new BasicHttpContext();
localContext2.setAttribute(ClientContext.USER_TOKEN, principal);
HttpGet httpget2 = new HttpGet("http://localhost:8080/");
HttpResponse response2 = httpclient.execute(httpget2, localContext2);
HttpEntity entity2 = response2.getEntity();
if (entity2 != null) {
entity2.consumeContent();
}
</pre>
</div>
</div>
 
</div>
 
</div><div class="navfooter"><hr><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="httpagent.html">Prev</a>&nbsp;</td><td width="20%" align="center">&nbsp;</td><td width="40%" align="right">&nbsp;</td></tr><tr><td width="40%" align="left" valign="top">Chapter&nbsp;5.&nbsp;HTTP client service&nbsp;</td><td width="20%" align="center"><a accesskey="h" href="index.html">Home</a></td><td width="40%" align="right" valign="top">&nbsp;</td></tr></table></div></body></html>
/ViaThinkSoft Java Utils/lib/httpcomponents-client-4.0.1/tutorial/html/preface.html
0,0 → 1,52
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Preface</title><link rel="stylesheet" href="css/hc-tutorial.css" type="text/css"><meta name="generator" content="DocBook XSL-NS Stylesheets V1.73.2"><link rel="start" href="index.html" title="HttpClient Tutorial"><link rel="up" href="index.html" title="HttpClient Tutorial"><link rel="prev" href="index.html" title="HttpClient Tutorial"><link rel="next" href="fundamentals.html" title="Chapter&nbsp;1.&nbsp;Fundamentals"></head><body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"><div xmlns:fo="http://www.w3.org/1999/XSL/Format" class="banner"><a class="bannerLeft" href="http://www.apache.org/" title="Apache Software Foundation"><img style="border:none;" src="images/asf_logo_wide.gif"></a><a class="bannerRight" href="http://hc.apache.org/httpcomponents-core/" title="Apache HttpComponents Core"><img style="border:none;" src="images/hc_logo.png"></a><div class="clear"></div></div><div class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="3" align="center">Preface</th></tr><tr><td width="20%" align="left"><a accesskey="p" href="index.html">Prev</a>&nbsp;</td><th width="60%" align="center">&nbsp;</th><td width="20%" align="right">&nbsp;<a accesskey="n" href="fundamentals.html">Next</a></td></tr></table><hr></div><div class="preface" lang="en"><div class="titlepage"><div><div><h2 class="title"><a name="preface"></a>Preface</h2></div></div></div>
<p>
The Hyper-Text Transfer Protocol (HTTP) is perhaps the most significant protocol used on the
Internet today. Web services, network-enabled appliances and the growth of network computing
continue to expand the role of the HTTP protocol beyond user-driven web browsers, while
increasing the number of applications that require HTTP support.
</p>
<p>
Although the java.net package provides basic functionality for accessing resources via HTTP,
it doesn't provide the full flexibility or functionality needed by many applications.
HttpClient seeks to fill this void by providing an efficient, up-to-date, and feature-rich
package implementing the client side of the most recent HTTP standards and recommendations.
</p>
<p>
Designed for extension while providing robust support for the base HTTP protocol, HttpClient
may be of interest to anyone building HTTP-aware client applications such as web browsers, web
service clients, or systems that leverage or extend the HTTP protocol for distributed
communication.
</p>
<div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="d4e20"></a>1.&nbsp;HttpClient scope</h2></div></div></div>
<div class="itemizedlist"><ul type="disc"><li>
<p>
Client-side HTTP transport library based on <a class="ulink" href="http://hc.apache.org/httpcomponents-core/index.html" target="_top">HttpCore</a>
</p>
</li><li>
<p>
Based on classic (blocking) I/O
</p>
</li><li>
<p>
Content agnostic
</p>
</li></ul></div>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="d4e30"></a>2.&nbsp;What HttpClient is NOT</h2></div></div></div>
<div class="itemizedlist"><ul type="disc"><li>
<p>
HttpClient is NOT a browser. It is a client side HTTP transport library.
HttpClient's purpose is to transmit and receive HTTP messages. HttpClient will not
attempt to cache content, execute javascript embedded in HTML pages, try to guess
content type, or reformat request / redirect location URIs, or other functionality
unrelated to the HTTP transport.
</p>
</li></ul></div>
</div>
 
</div><div class="navfooter"><hr><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="index.html">Prev</a>&nbsp;</td><td width="20%" align="center">&nbsp;</td><td width="40%" align="right">&nbsp;<a accesskey="n" href="fundamentals.html">Next</a></td></tr><tr><td width="40%" align="left" valign="top">HttpClient Tutorial&nbsp;</td><td width="20%" align="center"><a accesskey="h" href="index.html">Home</a></td><td width="40%" align="right" valign="top">&nbsp;Chapter&nbsp;1.&nbsp;Fundamentals</td></tr></table></div></body></html>
/ViaThinkSoft Java Utils/lib/httpcomponents-client-4.0.1/tutorial/html/statemgmt.html
0,0 → 1,346
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Chapter&nbsp;3.&nbsp;HTTP state management</title><link rel="stylesheet" href="css/hc-tutorial.css" type="text/css"><meta name="generator" content="DocBook XSL-NS Stylesheets V1.73.2"><link rel="start" href="index.html" title="HttpClient Tutorial"><link rel="up" href="index.html" title="HttpClient Tutorial"><link rel="prev" href="connmgmt.html" title="Chapter&nbsp;2.&nbsp;Connection management"><link rel="next" href="authentication.html" title="Chapter&nbsp;4.&nbsp;HTTP authentication"></head><body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"><div xmlns:fo="http://www.w3.org/1999/XSL/Format" class="banner"><a class="bannerLeft" href="http://www.apache.org/" title="Apache Software Foundation"><img style="border:none;" src="images/asf_logo_wide.gif"></a><a class="bannerRight" href="http://hc.apache.org/httpcomponents-core/" title="Apache HttpComponents Core"><img style="border:none;" src="images/hc_logo.png"></a><div class="clear"></div></div><div class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="3" align="center">Chapter&nbsp;3.&nbsp;HTTP state management</th></tr><tr><td width="20%" align="left"><a accesskey="p" href="connmgmt.html">Prev</a>&nbsp;</td><th width="60%" align="center">&nbsp;</th><td width="20%" align="right">&nbsp;<a accesskey="n" href="authentication.html">Next</a></td></tr></table><hr></div><div class="chapter" lang="en"><div class="titlepage"><div><div><h2 class="title"><a name="statemgmt"></a>Chapter&nbsp;3.&nbsp;HTTP state management</h2></div></div></div>
<p>Originally HTTP was designed as a stateless, request / response oriented protocol that
made no special provisions for stateful sessions spanning across several logically related
request / response exchanges. As HTTP protocol grew in popularity and adoption more and more
systems began to use it for applications it was never intended for, for instance as a
transport for e-commerce applications. Thus, the support for state management became a
necessity.</p>
<p>Netscape Communications, at that time a leading developer of web client and server
software, implemented support for HTTP state management in their products based on a
proprietary specification. Later, Netscape tried to standardise the mechanism by publishing
a specification draft. Those efforts contributed to the formal specification defined through
the RFC standard track. However, state management in a significant number of applications is
still largely based on the Netscape draft and is incompatible with the official
specification. All major developers of web browsers felt compelled to retain compatibility
with those applications greatly contributing to the fragmentation of standards
compliance.</p>
<div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="d4e655"></a>3.1.&nbsp;HTTP cookies</h2></div></div></div>
<p>Cookie is a token or short packet of state information that the HTTP agent and the
target server can exchange to maintain a session. Netscape engineers used to refer to it
as as a "magic cookie" and the name stuck.</p>
<p>HttpClient uses <code class="interfacename">Cookie</code> interface to represent an
abstract cookie token. In its simples form an HTTP cookie is merely a name / value pair.
Usually an HTTP cookie also contains a number of attributes such as version, a domain
for which is valid, a path that specifies the subset of URLs on the origin server to
which this cookie applies, and maximum period of time the cookie is valid for.</p>
<p><code class="interfacename">SetCookie</code> interface represents a
<code class="literal">Set-Cookie</code> response header sent by the origin server to the HTTP
agent in order to maintain a conversational state.
<code class="interfacename">SetCookie2</code> interface extends SetCookie with
<code class="literal">Set-Cookie2</code> specific methods.</p>
<p><code class="interfacename">ClientCookie</code> interface extends
<code class="interfacename">Cookie</code> interface with additional client specific
functionality such ability to retrieve original cookie attributes exactly as they were
specified by the origin server. This is important for generating the
<code class="literal">Cookie</code> header because some cookie specifications require that the
<code class="literal">Cookie</code> header should include certain attributes only if they were
specified in the <code class="literal">Set-Cookie</code> or <code class="literal">Set-Cookie2</code>
header.</p>
<div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="d4e672"></a>3.1.1.&nbsp;Cookie versions</h3></div></div></div>
<p>Cookies compatible with Netscape draft specification but non-compliant with the
official specification are considered to be of version 0. Standard compliant cookies
are expected to have version 1. HttpClient may handle cookies differently depending
on the version.</p>
<p>Here is an example of re-creating a Netscape cookie:</p>
<pre class="programlisting">
BasicClientCookie netscapeCookie = new BasicClientCookie("name", "value");
netscapeCookie.setVersion(0);
netscapeCookie.setDomain(".mycompany.com");
netscapeCookie.setPath("/");
</pre>
<p>Here is an example of re-creating a standard cookie. Please note that standard
compliant cookie must retain all attributes as sent by the origin server:</p>
<pre class="programlisting">
BasicClientCookie stdCookie = new BasicClientCookie("name", "value");
stdCookie.setVersion(1);
stdCookie.setDomain(".mycompany.com");
stdCookie.setPath("/");
stdCookie.setSecure(true);
// Set attributes EXACTLY as sent by the server
stdCookie.setAttribute(ClientCookie.VERSION_ATTR, "1");
stdCookie.setAttribute(ClientCookie.DOMAIN_ATTR, ".mycompany.com");
</pre>
<p>Here is an example of re-creating a <code class="literal">Set-Cookie2</code> compliant
cookie. Please note that standard compliant cookie must retain all attributes as
sent by the origin server:</p>
<pre class="programlisting">
BasicClientCookie2 stdCookie = new BasicClientCookie2("name", "value");
stdCookie.setVersion(1);
stdCookie.setDomain(".mycompany.com");
stdCookie.setPorts(new int[] {80,8080});
stdCookie.setPath("/");
stdCookie.setSecure(true);
// Set attributes EXACTLY as sent by the server
stdCookie.setAttribute(ClientCookie.VERSION_ATTR, "1");
stdCookie.setAttribute(ClientCookie.DOMAIN_ATTR, ".mycompany.com");
stdCookie.setAttribute(ClientCookie.PORT_ATTR, "80,8080");
</pre>
</div>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="d4e682"></a>3.2.&nbsp;Cookie specifications</h2></div></div></div>
<p><code class="interfacename">CookieSpec</code> interface represents a cookie management
specification. Cookie management specification is expected to enforce:</p>
<div class="itemizedlist"><ul type="disc"><li>
<p>rules of parsing <code class="literal">Set-Cookie</code> and optionally
<code class="literal">Set-Cookie2</code> headers.</p>
</li><li>
<p>rules of validation of parsed cookies.</p>
</li><li>
<p>formatting of <code class="literal">Cookie</code> header for a given host, port and path
of origin.</p>
</li></ul></div>
<p>HttpClient ships with several <code class="interfacename">CookieSpec</code>
implementations:</p>
<div class="itemizedlist"><ul type="disc"><li>
<p>
<b>Netscape draft:&nbsp;</b>
This specification conforms to the original draft specification published
by Netscape Communications. It should be avoided unless absolutely necessary
for compatibility with legacy code.
</p>
</li><li>
<p>
<b>RFC 2109:&nbsp;</b>
Older version of the official HTTP state management specification
superseded by RFC 2965.
</p>
</li><li>
<p>
<b>RFC 2965:&nbsp;</b>
The official HTTP state management specification.
</p>
</li><li>
<p>
<b>Browser compatibility:&nbsp;</b>
This implementations strives to closely mimic (mis)behavior of common web
browser applications such as Microsoft Internet Explorer and Mozilla
FireFox.
</p>
</li><li>
<p>
<b>Best match:&nbsp;</b>
'Meta' cookie specification that picks up a cookie policy based on the
format of cookies sent with the HTTP response. It basically aggregates all
above implementations into one class.
</p>
</li></ul></div>
<p>It is strongly recommended to use the <code class="literal">Best Match</code> policy and let
HttpClient pick up an appropriate compliance level at runtime based on the execution
context.</p>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="d4e721"></a>3.3.&nbsp;HTTP cookie and state management parameters</h2></div></div></div>
<p>These are parameters that be used to customize HTTP state management and behaviour of
individual cookie specifications:</p>
<div class="itemizedlist"><ul type="disc"><li>
<p>
<b>'http.protocol.cookie-datepatterns':&nbsp;</b>
defines valid date patterns to be used for parsing non-standard
<code class="literal">expires</code> attribute. Only required for compatibility
with non-compliant servers that still use <code class="literal">expires</code> defined
in the Netscape draft instead of the standard <code class="literal">max-age</code>
attribute. This parameter expects a value of type
<code class="interfacename">java.util.Collection</code>. The collection
elements must be of type <code class="classname">java.lang.String</code> compatible
with the syntax of <code class="classname">java.text.SimpleDateFormat</code>. If
this parameter is not set the choice of a default value is
<code class="interfacename">CookieSpec</code> implementation specific.
Please note this parameter applies
</p>
</li><li>
<p>
<b>'http.protocol.single-cookie-header':&nbsp;</b>
defines whether cookies should be forced into a single
<code class="literal">Cookie</code> request header. Otherwise, each cookie is
formatted as a separate <code class="literal">Cookie</code> header. This parameter
expects a value of type <code class="classname">java.lang.Boolean</code>. If this
parameter is not set the choice of a default value is CookieSpec
implementation specific. Please note this parameter applies to strict cookie
specifications (RFC 2109 and RFC 2965) only. Browser compatibility and
netscape draft policies will always put all cookies into one request
header.
</p>
</li><li>
<p>
<b>'http.protocol.cookie-policy':&nbsp;</b>
defines the name of a cookie specification to be used for HTTP state
management. This parameter expects a value of type
<code class="classname">java.lang.String</code>. If this parameter is not set
valid date patterns are <code class="interfacename">CookieSpec</code>
implementation specific.
</p>
</li></ul></div>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="d4e749"></a>3.4.&nbsp;Cookie specification registry</h2></div></div></div>
<p>HttpClient maintains a registry of available cookie specifications using
<code class="classname">CookieSpecRegistry</code> class. The following specifications are
registered per default:</p>
<div class="itemizedlist"><ul type="disc"><li>
<p>
<b>compatibility:&nbsp;</b>
Browser compatibility (lenient policy).
</p>
</li><li>
<p>
<b>netscape:&nbsp;</b>
Netscape draft.
</p>
</li><li>
<p>
<b>rfc2109:&nbsp;</b>
RFC 2109 (outdated strict policy).
</p>
</li><li>
<p>
<b>rfc2965:&nbsp;</b>
RFC 2965 (standard conformant strict policy).
</p>
</li><li>
<p>
<b>best-match:&nbsp;</b>
Best match meta-policy.
</p>
</li></ul></div>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="d4e774"></a>3.5.&nbsp;Choosing cookie policy</h2></div></div></div>
<p>Cookie policy can be set at the HTTP client and overridden on the HTTP request level
if required.</p>
<pre class="programlisting">
HttpClient httpclient = new DefaultHttpClient();
// force strict cookie policy per default
httpclient.getParams().setParameter(
ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2965);
 
HttpGet httpget = new HttpGet("http://www.broken-server.com/");
// Override the default policy for this request
httpget.getParams().setParameter(
ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
</pre>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="d4e778"></a>3.6.&nbsp;Custom cookie policy</h2></div></div></div>
<p>In order to implement a custom cookie policy one should create a custom implementation
of <code class="interfacename">CookieSpec</code> interface, create a
<code class="interfacename">CookieSpecFactory</code> implementation to create and
initialize instances of the custom specification and register the factory with
HttpClient. Once the custom specification has been registered, it can be activated the
same way as the standard cookie specifications.</p>
<pre class="programlisting">
CookieSpecFactory csf = new CookieSpecFactory() {
public CookieSpec newInstance(HttpParams params) {
return new BrowserCompatSpec() {
@Override
public void validate(Cookie cookie, CookieOrigin origin)
throws MalformedCookieException {
// Oh, I am easy
}
};
}
};
 
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getCookieSpecs().register("easy", csf);
httpclient.getParams().setParameter(
ClientPNames.COOKIE_POLICY, "easy");
</pre>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="d4e784"></a>3.7.&nbsp;Cookie persistence</h2></div></div></div>
<p>HttpClient can work with any physical representation of a persistent cookie store that
implements the <code class="interfacename">CookieStore</code> interface. The default
<code class="interfacename">CookieStore</code> implementation called
<code class="classname">BasicClientCookie</code> is a simple implementation backed by a
<code class="classname">java.util.ArrayList</code>. Cookies stored in an
<code class="classname">BasicClientCookie</code> object are lost when the container object
get garbage collected. Users can provide more complex implementations if
necessary.</p>
<pre class="programlisting">
DefaultHttpClient httpclient = new DefaultHttpClient();
// Create a local instance of cookie store
CookieStore cookieStore = new MyCookieStore();
// Populate cookies if needed
BasicClientCookie cookie = new BasicClientCookie("name", "value");
cookie.setVersion(0);
cookie.setDomain(".mycompany.com");
cookie.setPath("/");
cookieStore.addCookie(cookie);
// Set the store
httpclient.setCookieStore(cookieStore);
</pre>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="d4e793"></a>3.8.&nbsp;HTTP state management and execution context</h2></div></div></div>
<p>In the course of HTTP request execution HttpClient adds the following state management
related objects to the execution context:</p>
<div class="itemizedlist"><ul type="disc"><li>
<p>
<b>'http.cookiespec-registry':&nbsp;</b>
<code class="classname">CookieSpecRegistry</code> instance representing the actual
cookie specification registry. The value of this attribute set in the local
context takes precedence over the default one.
</p>
</li><li>
<p>
<b>'http.cookie-spec':&nbsp;</b>
<code class="interfacename">CookieSpec</code> instance representing the actual
cookie specification.
</p>
</li><li>
<p>
<b>'http.cookie-origin':&nbsp;</b>
<code class="classname">CookieOrigin</code> instance representing the actual
details of the origin server.
</p>
</li><li>
<p>
<b>'http.cookie-store':&nbsp;</b>
<code class="interfacename">CookieStore</code> instance represents the actual
cookie store. The value of this attribute set in the local context takes
precedence over the default one.
</p>
</li></ul></div>
<p>The local <code class="interfacename">HttpContext</code> object can be used to customize
the HTTP state management context prior to request execution or examine its state after
the request has been executed:</p>
<pre class="programlisting">
HttpClient httpclient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpget = new HttpGet("http://localhost:8080/");
HttpResponse response = httpclient.execute(httpget, localContext);
 
CookieOrigin cookieOrigin = (CookieOrigin) localContext.getAttribute(
ClientContext.COOKIE_ORIGIN);
System.out.println("Cookie origin: " + cookieOrigin);
CookieSpec cookieSpec = (CookieSpec) localContext.getAttribute(
ClientContext.COOKIE_SPEC);
System.out.println("Cookie spec used: " + cookieSpec);
</pre>
</div>
<div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="d4e820"></a>3.9.&nbsp;Per user / thread state management</h2></div></div></div>
<p>One can use an individual local execution context in order to implement per user (or
per thread) state management. Cookie specification registry and cookie store defined in
the local context will take precedence over the default ones set at the HTTP client
level.</p>
<pre class="programlisting">
HttpClient httpclient = new DefaultHttpClient();
// Create a local instance of cookie store
CookieStore cookieStore = new BasicCookieStore();
// Create local HTTP context
HttpContext localContext = new BasicHttpContext();
// Bind custom cookie store to the local context
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
HttpGet httpget = new HttpGet("http://www.google.com/");
// Pass local context as a parameter
HttpResponse response = httpclient.execute(httpget, localContext);
</pre>
</div>
</div><div class="navfooter"><hr><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="connmgmt.html">Prev</a>&nbsp;</td><td width="20%" align="center">&nbsp;</td><td width="40%" align="right">&nbsp;<a accesskey="n" href="authentication.html">Next</a></td></tr><tr><td width="40%" align="left" valign="top">Chapter&nbsp;2.&nbsp;Connection management&nbsp;</td><td width="20%" align="center"><a accesskey="h" href="index.html">Home</a></td><td width="40%" align="right" valign="top">&nbsp;Chapter&nbsp;4.&nbsp;HTTP authentication</td></tr></table></div></body></html>
/ViaThinkSoft Java Utils/lib/httpcomponents-client-4.0.1/tutorial/html/index.html
0,0 → 1,40
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>HttpClient Tutorial</title><link rel="stylesheet" href="css/hc-tutorial.css" type="text/css"><meta name="generator" content="DocBook XSL-NS Stylesheets V1.73.2"><link rel="start" href="index.html" title="HttpClient Tutorial"><link rel="next" href="preface.html" title="Preface"></head><body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"><div xmlns:fo="http://www.w3.org/1999/XSL/Format" class="banner"><a class="bannerLeft" href="http://www.apache.org/" title="Apache Software Foundation"><img style="border:none;" src="images/asf_logo_wide.gif"></a><a class="bannerRight" href="http://hc.apache.org/httpcomponents-core/" title="Apache HttpComponents Core"><img style="border:none;" src="images/hc_logo.png"></a><div class="clear"></div></div><div class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="3" align="center">HttpClient Tutorial</th></tr><tr><td width="20%" align="left">&nbsp;</td><th width="60%" align="center">&nbsp;</th><td width="20%" align="right">&nbsp;<a accesskey="n" href="preface.html">Next</a></td></tr></table><hr></div><div class="book" lang="en"><div class="titlepage"><div><div><h1 class="title"><a name="d4e1"></a>HttpClient Tutorial</h1></div><div><div class="authorgroup">
<div class="author"><h3 class="author"><span class="firstname">Oleg</span> <span class="surname">Kalnichevski</span></h3></div>
</div></div><div><p class="releaseinfo">4.0.1</p></div><div><div class="legalnotice"><a name="d4e9"></a>
<p>
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
</p>
<p>
<a class="ulink" href="http://www.apache.org/licenses/LICENSE-2.0" target="_top">http://www.apache.org/licenses/LICENSE-2.0</a>
</p>
<p>
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
</p>
</div></div></div><hr></div><div class="toc"><dl><dt><span class="preface"><a href="preface.html">Preface</a></span></dt><dd><dl><dt><span class="section"><a href="preface.html#d4e20">1. HttpClient scope</a></span></dt><dt><span class="section"><a href="preface.html#d4e30">2. What HttpClient is NOT</a></span></dt></dl></dd><dt><span class="chapter"><a href="fundamentals.html">1. Fundamentals</a></span></dt><dd><dl><dt><span class="section"><a href="fundamentals.html#d4e37">1.1. Request execution</a></span></dt><dd><dl><dt><span class="section"><a href="fundamentals.html#d4e43">1.1.1. HTTP request</a></span></dt><dt><span class="section"><a href="fundamentals.html#d4e72">1.1.2. HTTP response</a></span></dt><dt><span class="section"><a href="fundamentals.html#d4e78">1.1.3. Working with message headers</a></span></dt><dt><span class="section"><a href="fundamentals.html#d4e93">1.1.4. HTTP entity</a></span></dt><dd><dl><dt><span class="section"><a href="fundamentals.html#d4e117">1.1.4.1. Repeatable entities</a></span></dt><dt><span class="section"><a href="fundamentals.html#d4e122">1.1.4.2. Using HTTP entities</a></span></dt></dl></dd><dt><span class="section"><a href="fundamentals.html#d4e143">1.1.5. Ensuring release of low level resources</a></span></dt><dt><span class="section"><a href="fundamentals.html#d4e152">1.1.6. Consuming entity content</a></span></dt><dt><span class="section"><a href="fundamentals.html#d4e164">1.1.7. Producing entity content</a></span></dt><dd><dl><dt><span class="section"><a href="fundamentals.html#d4e179">1.1.7.1. Dynamic content entities</a></span></dt><dt><span class="section"><a href="fundamentals.html#d4e186">1.1.7.2. HTML forms</a></span></dt><dt><span class="section"><a href="fundamentals.html#d4e194">1.1.7.3. Content chunking</a></span></dt></dl></dd><dt><span class="section"><a href="fundamentals.html#d4e199">1.1.8. Response handlers</a></span></dt></dl></dd><dt><span class="section"><a href="fundamentals.html#d4e205">1.2. HTTP execution context</a></span></dt><dt><span class="section"><a href="fundamentals.html#d4e246">1.3. Exception handling</a></span></dt><dd><dl><dt><span class="section"><a href="fundamentals.html#d4e251">1.3.1. HTTP transport safety</a></span></dt><dt><span class="section"><a href="fundamentals.html#d4e255">1.3.2. Idempotent methods</a></span></dt><dt><span class="section"><a href="fundamentals.html#d4e267">1.3.3. Automatic exception recovery</a></span></dt><dt><span class="section"><a href="fundamentals.html#d4e280">1.3.4. Request retry handler</a></span></dt></dl></dd><dt><span class="section"><a href="fundamentals.html#d4e285">1.4. Aborting requests</a></span></dt><dt><span class="section"><a href="fundamentals.html#d4e290">1.5. HTTP protocol interceptors</a></span></dt><dt><span class="section"><a href="fundamentals.html#d4e298">1.6. HTTP parameters</a></span></dt><dd><dl><dt><span class="section"><a href="fundamentals.html#d4e316">1.6.1. Parameter hierarchies</a></span></dt><dt><span class="section"><a href="fundamentals.html#d4e327">1.6.2. HTTP parameters beans</a></span></dt></dl></dd><dt><span class="section"><a href="fundamentals.html#d4e337">1.7. HTTP request execution parameters</a></span></dt></dl></dd><dt><span class="chapter"><a href="connmgmt.html">2. Connection management</a></span></dt><dd><dl><dt><span class="section"><a href="connmgmt.html#d4e391">2.1. Connection parameters</a></span></dt><dt><span class="section"><a href="connmgmt.html#d4e438">2.2. Connection persistence</a></span></dt><dt><span class="section"><a href="connmgmt.html#d4e442">2.3. HTTP connection routing</a></span></dt><dd><dl><dt><span class="section"><a href="connmgmt.html#d4e446">2.3.1. Route computation</a></span></dt><dt><span class="section"><a href="connmgmt.html#d4e462">2.3.2. Secure HTTP connections</a></span></dt></dl></dd><dt><span class="section"><a href="connmgmt.html#d4e465">2.4. HTTP route parameters</a></span></dt><dt><span class="section"><a href="connmgmt.html#d4e484">2.5. Socket factories</a></span></dt><dd><dl><dt><span class="section"><a href="connmgmt.html#d4e492">2.5.1. Secure socket layering</a></span></dt><dt><span class="section"><a href="connmgmt.html#d4e497">2.5.2. SSL/TLS customization</a></span></dt><dt><span class="section"><a href="connmgmt.html#d4e506">2.5.3. Hostname verification</a></span></dt></dl></dd><dt><span class="section"><a href="connmgmt.html#d4e532">2.6. Protocol schemes</a></span></dt><dt><span class="section"><a href="connmgmt.html#d4e540">2.7. HttpClient proxy configuration</a></span></dt><dt><span class="section"><a href="connmgmt.html#d4e550">2.8. HTTP connection managers</a></span></dt><dd><dl><dt><span class="section"><a href="connmgmt.html#d4e552">2.8.1. Connection operators</a></span></dt><dt><span class="section"><a href="connmgmt.html#d4e563">2.8.2. Managed connections and connection managers</a></span></dt><dt><span class="section"><a href="connmgmt.html#d4e588">2.8.3. Simple connection manager</a></span></dt><dt><span class="section"><a href="connmgmt.html#d4e596">2.8.4. Pooling connection manager</a></span></dt><dt><span class="section"><a href="connmgmt.html#d4e604">2.8.5. Connection manager shutdown</a></span></dt></dl></dd><dt><span class="section"><a href="connmgmt.html#d4e608">2.9. Connection management parameters</a></span></dt><dt><span class="section"><a href="connmgmt.html#d4e629">2.10. Multithreaded request execution</a></span></dt><dt><span class="section"><a href="connmgmt.html#d4e638">2.11. Connection eviction policy</a></span></dt><dt><span class="section"><a href="connmgmt.html#d4e645">2.12. Connection keep alive strategy</a></span></dt></dl></dd><dt><span class="chapter"><a href="statemgmt.html">3. HTTP state management</a></span></dt><dd><dl><dt><span class="section"><a href="statemgmt.html#d4e655">3.1. HTTP cookies</a></span></dt><dd><dl><dt><span class="section"><a href="statemgmt.html#d4e672">3.1.1. Cookie versions</a></span></dt></dl></dd><dt><span class="section"><a href="statemgmt.html#d4e682">3.2. Cookie specifications</a></span></dt><dt><span class="section"><a href="statemgmt.html#d4e721">3.3. HTTP cookie and state management parameters</a></span></dt><dt><span class="section"><a href="statemgmt.html#d4e749">3.4. Cookie specification registry</a></span></dt><dt><span class="section"><a href="statemgmt.html#d4e774">3.5. Choosing cookie policy</a></span></dt><dt><span class="section"><a href="statemgmt.html#d4e778">3.6. Custom cookie policy</a></span></dt><dt><span class="section"><a href="statemgmt.html#d4e784">3.7. Cookie persistence</a></span></dt><dt><span class="section"><a href="statemgmt.html#d4e793">3.8. HTTP state management and execution context</a></span></dt><dt><span class="section"><a href="statemgmt.html#d4e820">3.9. Per user / thread state management</a></span></dt></dl></dd><dt><span class="chapter"><a href="authentication.html">4. HTTP authentication</a></span></dt><dd><dl><dt><span class="section"><a href="authentication.html#d4e829">4.1. User credentials</a></span></dt><dt><span class="section"><a href="authentication.html#d4e841">4.2. Authentication schemes</a></span></dt><dt><span class="section"><a href="authentication.html#d4e869">4.3. HTTP authentication parameters</a></span></dt><dt><span class="section"><a href="authentication.html#d4e884">4.4. Authentication scheme registry</a></span></dt><dt><span class="section"><a href="authentication.html#d4e903">4.5. Credentials provider</a></span></dt><dt><span class="section"><a href="authentication.html#d4e914">4.6. HTTP authentication and execution context</a></span></dt><dt><span class="section"><a href="authentication.html#d4e950">4.7. Preemptive authentication</a></span></dt><dt><span class="section"><a href="authentication.html#ntlm">4.8. NTLM Authentication</a></span></dt><dd><dl><dt><span class="section"><a href="authentication.html#d4e963">4.8.1. NTLM connection persistence</a></span></dt></dl></dd></dl></dd><dt><span class="chapter"><a href="httpagent.html">5. HTTP client service</a></span></dt><dd><dl><dt><span class="section"><a href="httpagent.html#d4e984">5.1. HttpClient facade</a></span></dt><dt><span class="section"><a href="httpagent.html#d4e1001">5.2. HttpClient parameters</a></span></dt><dt><span class="section"><a href="httpagent.html#d4e1049">5.3. Automcatic redirect handling</a></span></dt><dt><span class="section"><a href="httpagent.html#d4e1056">5.4. HTTP client and execution context</a></span></dt></dl></dd><dt><span class="chapter"><a href="advanced.html">6. Advanced topics</a></span></dt><dd><dl><dt><span class="section"><a href="advanced.html#d4e1063">6.1. Custom client connections</a></span></dt><dt><span class="section"><a href="advanced.html#stateful_conn">6.2. Stateful HTTP connections</a></span></dt><dd><dl><dt><span class="section"><a href="advanced.html#d4e1089">6.2.1. User token handler</a></span></dt><dt><span class="section"><a href="advanced.html#d4e1099">6.2.2. User token and execution context</a></span></dt><dd><dl><dt><span class="section"><a href="advanced.html#d4e1110">6.2.2.1. Persistent stateful connections</a></span></dt></dl></dd></dl></dd></dl></dd></dl></div>
 
 
</div><div class="navfooter"><hr><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left">&nbsp;</td><td width="20%" align="center">&nbsp;</td><td width="40%" align="right">&nbsp;<a accesskey="n" href="preface.html">Next</a></td></tr><tr><td width="40%" align="left" valign="top">&nbsp;</td><td width="20%" align="center">&nbsp;</td><td width="40%" align="right" valign="top">&nbsp;Preface</td></tr></table></div></body></html>
/ViaThinkSoft Java Utils/lib/httpcomponents-client-4.0.1/tutorial/pdf/httpclient-tutorial.pdf
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/ViaThinkSoft Java Utils/lib/httpcomponents-client-4.0.1/NTLM_SUPPORT.txt
0,0 → 1,147
NTLM support in HttpClient 4.x
==============================
 
Currently HttpClient 4.0 does not provide support for the NTLM authentication
scheme out of the box and probably never will. The reasons for that are legal
rather than technical.
 
Background
==========
NTLM is a proprietary authentication scheme developed by Microsoft and
optimized for Windows operating system.
 
Until year 2008 there was no official, publicly available, complete
documentation of the protocol. Unofficial 3rd party protocol descriptions
existed [1] as a result of reverse-engineering efforts. It was not really
known whether the protocol based on the reverse-engineering were complete
or even correct.
 
Microsoft published MS-NLMP [2] and MS-NTHT [3] specifications in February
2008 as a part of its Interoperability Principles initiative [4].
Unfortunately, it is still not entirely clear whether NTLM encryption
algorithms are covered by any patents held by Microsoft, which would make
commercial users of open-source NTLM implementations liable for the use of
Microsoft intellectual property.
Enabling NTLM support in HttpClient 4.x
=======================================
The good news is HttpClient is fully NTLM capable right out of the box.
HttpClient ships with the NTLM authentication scheme, which, if configured
to use an external NTLM engine, can handle NTLM challenges and authenticate
against NTLM servers.
 
-----------------------------------------------------------
public interface NTLMEngine {
 
String generateType1Msg(
String domain,
String workstation) throws NTLMEngineException;
String generateType3Msg(
String username,
String password,
String domain,
String workstation,
String challenge) throws NTLMEngineException;
 
}
-----------------------------------------------------------
 
Using Samba JCIFS as an NTLM engine
===================================
Follow these instructions to build an NTLMEngine implementation using JCIFS
library
 
=========== !!!! DISCLAIMER !!!! ===========
HttpComponents project DOES _NOT_ SUPPORT the code provided below. Use it as
is at your own discretion.
 
* Download the latest jcifs library from the Samba web site [5]
* Implement NTLMEngine interface
-----------------------------------------------------------
import jcifs.ntlmssp.Type1Message;
import jcifs.ntlmssp.Type2Message;
import jcifs.ntlmssp.Type3Message;
import jcifs.util.Base64;
 
import org.apache.http.impl.auth.NTLMEngine;
import org.apache.http.impl.auth.NTLMEngineException;
 
public class JCIFSEngine implements NTLMEngine {
 
public String generateType1Msg(
String domain,
String workstation) throws NTLMEngineException {
 
Type1Message t1m = new Type1Message(
Type1Message.getDefaultFlags(),
domain,
workstation);
return Base64.encode(t1m.toByteArray());
}
 
public String generateType3Msg(
String username,
String password,
String domain,
String workstation,
String challenge) throws NTLMEngineException {
Type2Message t2m;
try {
t2m = new Type2Message(Base64.decode(challenge));
} catch (IOException ex) {
throw new NTLMEngineException("Invalid Type2 message", ex);
}
Type3Message t3m = new Type3Message(
t2m,
password,
domain,
username,
workstation);
return Base64.encode(t3m.toByteArray());
}
 
}
-----------------------------------------------------------
* Implement AuthSchemeFactory interface
-----------------------------------------------------------
import org.apache.http.auth.AuthScheme;
import org.apache.http.auth.AuthSchemeFactory;
import org.apache.http.impl.auth.NTLMScheme;
import org.apache.http.params.HttpParams;
 
public class NTLMSchemeFactory implements AuthSchemeFactory {
 
public AuthScheme newInstance(final HttpParams params) {
return new NTLMScheme(new JCIFSEngine());
}
 
}
-----------------------------------------------------------
* Register NTLMSchemeFactory with the HttpClient instance you want to NTLM
enable.
-----------------------------------------------------------
httpclient.getAuthSchemes().register("ntlm", new NTLMSchemeFactory());
-----------------------------------------------------------
* Set NTCredentials for the web server you are going to access.
-----------------------------------------------------------
httpclient.getCredentialsProvider().setCredentials(
new AuthScope("myserver", -1),
new NTCredentials("username", "password", "MYSERVER", "MYDOMAIN"));
-----------------------------------------------------------
* You are done.
 
 
Why this code is not distributed with HttpClient
================================================
JCIFS is licensed under the Lesser General Public License (LGPL). This license
is not compatible with the Apache Licenses under which all Apache Software is
released. Lawyers of the Apache Software Foundation are currently investigating
under which conditions Apache software is allowed to make use of LGPL software.
 
-----------------------------------------------------------
[1] http://davenport.sourceforge.net/ntlm.html
[2] http://download.microsoft.com/download/a/e/6/ae6e4142-aa58-45c6-8dcf-a657e5900cd3/%5BMS-NLMP%5D.pdf
[3] http://download.microsoft.com/download/a/e/6/ae6e4142-aa58-45c6-8dcf-a657e5900cd3/%5BMS-NTHT%5D.pdf
[4] http://www.microsoft.com/interop/principles/default.mspx
[5] http://jcifs.samba.org/
/ViaThinkSoft Java Utils/lib/httpcomponents-client-4.0.1/lib/apache-mime4j-0.6.jar
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/ViaThinkSoft Java Utils/lib/httpcomponents-client-4.0.1/lib/commons-codec-1.3.jar
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/ViaThinkSoft Java Utils/lib/httpcomponents-client-4.0.1/lib/httpmime-4.0.1.jar
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/ViaThinkSoft Java Utils/lib/httpcomponents-client-4.0.1/lib/httpcore-4.0.1.jar
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/ViaThinkSoft Java Utils/lib/httpcomponents-client-4.0.1/lib/commons-logging-1.1.1.jar
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/ViaThinkSoft Java Utils/lib/httpcomponents-client-4.0.1/lib/httpclient-4.0.1.jar
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/ViaThinkSoft Java Utils/lib/httpcomponents-client-4.0.1/RELEASE_NOTES.txt
0,0 → 1,623
Release 4.0.1
-------------------
 
This is a bug fix release that addresses a number of issues discovered since
the previous stable release. None of the fixed bugs is considered critical.
Most notably this release eliminates eliminates dependency on JCIP annotations.
 
This release is also expected to improve performance by 5 to 10% due to
elimination of unnecessary Log object lookups by short-lived components.
 
Changelog
-------------------
 
* [HTTPCLIENT-895] Eliminated Log object lookups by short-lived components
impairing performance.
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* [HTTPCLIENT-885] URLEncodedUtils now correctly parses form-url-encoded
entities that specify a charset.
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* [HTTPCLIENT-884] UrlEncodedFormEntity now sets charset on the Content-Type
header.
Contributed by Jared Jacobs <jmjacobs at cs.stanford.edu>
* [HTTPCLIENT-883] SO_TIMEOUT is not reset on persistent (re-used) connections.
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* [HTTPCLIENT-882] Auth state is now correctly updated if a successful NTLM
authentication results in a redirect. This is a minor bug as HttpClient
manages to recover from the problem automatically.
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* [HTTPCLIENT-881] Fixed race condition in AbstractClientConnAdapter that makes
it possible for an aborted connection to be returned to the pool.
Contributed by Tim Boemker <tboemker at elynx.com> and
Oleg Kalnichevski <olegk at apache.org>
 
* [HTTPCLIENT-866] Removed dependency on jcip-annotations.jar.
Contributed by Oleg Kalnichevski <olegk at apache.org>
and Sebastian Bazley <sebb at apache.org>
 
 
Release 4.0
-------------------
 
HttpClient 4.0 represents a complete, ground-up redesign and almost a complete
rewrite of the HttpClient 3.x codeline. This release finally addresses several
design flaws that existed since the 1.0 release and could not be fixed without
a major code overhaul and breaking API compatibility.
 
 
Architectural changes
---------------------
 
* Redesign of the HttpClient internals addressing all known major
architectural shortcomings of the 3.x codeline.
 
* Cleaner, more flexible and expressive API.
 
* More modular structure.
 
* Better performance and smaller memory footprint due to a more efficient HTTP
transport based on HttpCore.
 
* Implementation of cross-cutting HTTP protocol aspects through protocol
interceptors.
 
* Improved connection management, better handling of persistent connections,
support for stateful connections
 
* Pluggable redirect and authentication handlers.
 
* Improved support for sending requests via a proxy or a chain of proxies
 
* More flexible SSL context customization
 
* Reduced intermediate garbage in the process of generating HTTP requests
and parsing HTTP responses
 
 
Important notes
-------------------
 
* Future releases of HttpMime module may be binary incompatible with this
release due to possible API changes in Apache Mime4J. Apache Mime4J is
still being actively developed and its API is considered unstable.
* HttpClient 4.0 is not fully binary compatible with 4.0 BETA1 release.
Some protected variables in connection management class have been
made final in order to help ensure their thread safety:
 
org.apache.http.conn.BasicEofSensorWatcher#attemptReuse
org.apache.http.conn.BasicEofSensorWatcher#managedConn
org.apache.http.impl.conn.DefaultClientConnectionOperator#schemeRegistry
org.apache.http.impl.conn.DefaultHttpRoutePlanner#schemeRegistry
org.apache.http.impl.conn.ProxySelectorRoutePlanner#schemeRegistry
org.apache.http.impl.conn.SingleClientConnManager#alwaysShutDown
org.apache.http.impl.conn.SingleClientConnManager#connOperator
org.apache.http.impl.conn.SingleClientConnManager#schemeRegistry
org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager#connOperator
org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager#schemeRegistry
 
Bug fixes since 4.0 BETA2 release
-------------------
 
* [HTTPCLIENT-861] URIUtils#resolve is now compatible with all examples given
in RFC 3986.
Contributed by Johannes Koch <johannes.koch at fit.fraunhofer.de>
 
* [HTTPCLIENT-860] HttpClient no longer converts redirects of PUT/POST to GET
for status codes 301, 302, 307, as required by the HTTP spec.
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* [HTTPCLIENT-859] CookieIdentityComparator now takes path attribute into
consideration when comparing cookies.
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* HttpClient will no longer send expired cookies back to the origin server.
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* [HTTPCLIENT-856] Proxy NTLM authentication no longer fails on a redirect to
a different host.
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* [HTTPCLIENT-841] Removed automatic connection release using garbage collection
due to a memory leak.
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* [HTTPCLIENT-853] Fixed bug causing invalid cookie origin port to be selected
when the target is accessed on the default port and the connection is
established via a proxy.
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* [HTTPCLIENT-852] Fixed bug causing automatically retried redirects fail with
CircularRedirectException.
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* Fixed problem with the default HTTP response parser failing to handle garbage
preceding a valid HTTP response.
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* NonRepeatableRequestExceptions now include the cause that the original
request failed.
Contributed by Sam Berlin <sberlin at apache.org>
 
* [HTTPCLIENT-837] Fixed problem with the wire log skipping zero byte values
if read one byte at a time.
Contributed by Kirill Safonov <ksafonov at swiftteams.com>
 
* [HTTPCLIENT-823] 'http.conn-manager.max-total' parameter can be adjusted
dynamically. However, the size of existing connection pools per route,
once allocated, will not be adjusted.
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* [HTTPCLIENT-822] Default socket factories to rethrow SocketTimeoutException
as ConnectTimeoutException in case of connect failure due to a time out.
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* [HTTPCLIENT-813] Fixed default port resolution. Invalid ports no longer
get replaced with the default port value.
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
Release 4.0 beta 2
-------------------
 
BETA2 is a maintenance release, which addresses a number of issues
discovered since the previous release.
 
The only significant new feature is an addition of an OSGi compliant
bundle combining HttpClient and HttpMime jars.
 
All upstream projects are strongly encouraged to upgrade.
 
* Fixed NPE in DefaultRequestDirector thrown when retrying a failed
request over a proxied connection.
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* [HTTPCLIENT-803] Fixed bug in SSL host verifier implementations
causing the SSL certificate to be rejected as invalid if the connection
is established using an IP address.
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* [HTTPCLIENT-806] DefaultHttpMethodRetryHandler will no longer retry
on ConnectExceptions.
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* DigestScheme can use an arbitrary digest algorithm requested by the
target server (such as SHA) as long as this algorithm is supported by
the Java runtime.
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* Fixed parsing and validation of RFC2109 compliant Set-Cookie headers
by the Best-Match cookie spec.
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* Fixed bug that can cause a managed connection to be returned from the
pool in an inconsistent state.
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
 
4.0 Beta 1
-------------------
 
BETA1 release brings yet another round of API enhancements and
improvements in the area of connection management. Among the most notable
ones is the capability to handle stateful connections such as persistent
NTLM connections and private key authenticated SSL connections.
 
This is the first API stable release of HttpClient 4.0. All further
releases in the 4.0 code line will maintain API compatibility with this
release.
 
There has been a number of important bug fixes since ALPHA4. All upstream
projects are encouraged to upgrade to the latest release.
 
Please note HttpClient currently provides only limited support for NTLM
authentication. For details please see NTLM_SUPPORT.txt.
 
-------------------
 
Changelog:
-------------------
 
* [HTTPCLIENT-790] Protocol interceptors are now correctly invoked when
executing CONNECT methods.
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* [HTTPCLIENT-668] Do not use static loggers.
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* [HTTPCLIENT-781] Respect Keep-Alive header's timeout value.
Contributed by Sam Berlin <sberlin at apache.org>
 
* [HTTPCLIENT-779] Top-level classes (HttpClient, and HttpGet, HttpPut
and similar HttpMethods) throw fewer checked exceptions.
Contributed by Sam Berlin <sberlin at apache.org>
 
* HttpClient will throw an exception if an attempt is made to retry
a request with a non-repeatable request entity.
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* Fixed request re-generation logic when retrying a failed request.
Auto-generated headers will no accumulate.
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* [HTTPCLIENT-424] Preemptive authentication no longer limited to BASIC
scheme only. HttpClient can be customized to authenticate preemptively
with DIGEST scheme.
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* [HTTPCLIENT-670] Pluggable hostname resolver.
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* [HTTPCLIENT-719] Clone support for HTTP request and cookie objects.
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* [HTTPCLIENT-776] Fixed concurrency issues with AbstractPoolEntry.
Contributed by Sam Berlin <sberlin at gmail.com>
 
* Resolved a long standing problem with HttpClient not taking into account
the user context when pooling / re-using connections. HttpClient now
correctly handles stateful / user specific connections such as persistent
NTLM connections and SSL connections with client side authentication.
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* [HTTPCLIENT-773] Improved handling of the 'expires' attribute by the
'Best Match' cookie spec.
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* Partial NTLM support (requires an external NTLM engine). For details see
NTLM_SUPPORT.txt
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* Redesigned local execution context management.
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
--------------------------------------
 
Release 4.0 Alpha 4
-------------------
 
ALPHA4 marks the completion of the overhaul of the connection management
code in HttpClient. All known shortcomings of the old HttpClient 3.x
connection management API have been addressed.
 
NTLM authentication remains the only missing major feature in the new
codeline that prevents us from moving awards the API freeze.
 
There has been a number of important bug fixes since ALPHA3. All upstream
projects are encouraged to upgrade to the latest release.
 
-------------------
 
HttpClient 3.x features that have NOT yet been ported:
-------------------
 
* NTLM authentication scheme
 
-------------------
 
Changelog:
-------------------
 
* [HTTPCLIENT-765] String.toLowerCase() / toUpperCase() should specify
Locale.ENGLISH
Contributed by Sebastian Bazley <sebb at apache.org>
 
* [HTTPCLIENT-769] Do not pool connection marked non-reusable.
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* [HTTPCLIENT-763] Fixed problem with AbstractClientConnAdapter#abortConnection()
not releasing the connection if called from the main execution thread while
there is no blocking I/O operation.
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* [HTTPCLIENT-652] Added optional state attribute to managed client connections.
This enables connection managers to correctly handle stateful connections.
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* [HTTPCLIENT-673] Revised max connections per route configuration
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* [HTTPCLIENT-753] Class Scheme and related classes moved to a separate package
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* [HTTPCLIENT-757] Improved request wrapping in the DefaultClientRequestDirector.
This also fixed the problem with the default proxy set at the client level
having no effect.
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* [HTTPCLIENT-734] Request abort will unblock the thread waiting for a connection
Contributed by Sam Berlin <sberlin at gmail.com>
 
* [HTTPCLIENT-759] Ensure release of connections back to the connection manager
on exceptions.
Contributed by Sam Berlin <sberlin at gmail.com>
 
* [HTTPCLIENT-758] Fixed the use of generics in AbstractHttpClient
#removeRequestInterceptorByClass and #removeResponseInterceptorByClass
Contributed by Johannes Koch <johannes.koch at fit.fraunhofer.de>
 
* [HTTPCLIENT-749] HttpParams beans
Contributed by Stojce Dimski <sdmiski at yahoo.it>
 
* [HTTPCLIENT-755] Workaround for known bugs in java.net.URI.resolve()
Bug ID: 4708535
Contributed by Johannes Koch <johannes.koch at fit.fraunhofer.de>
 
--------------------------------------
 
Release 4.0 Alpha 3
-------------------
 
ALPHA3 release brings another round of API refinements and improvements in
functionality. As of this release HttpClient requires Java 5 compatible
runtime environment and takes full advantage of generics and new concurrency
primitives.
 
This release also introduces new default cookie policy that selects a cookie
specification depending on the format of cookies sent by the target host.
It is no longer necessary to know beforehand what kind of HTTP cookie support
the target host provides. HttpClient is now able to pick up either a lenient
or a strict cookie policy depending on the compliance level of the target host.
 
Another notable improvement is a completely reworked support for multipart
entities based on Apache mime4j library.
 
-------------------
 
HttpClient 3.x features that have NOT yet been ported:
-------------------
 
* NTLM authentication scheme
 
-------------------
 
Changelog:
-------------------
 
* [HTTPCLIENT-742] common interface for HttpRoute and RouteTracker
Contributed by Roland Weber <rolandw at apache.org>
 
* [HTTPCLIENT-741] Fixed concurrency issues in AbstractClientConnAdapter.
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* [HTTPCLIENT-726] testcase for spurious wakeups in ThreadSafeClientConnManager
Contributed by Roland Weber <rolandw at apache.org>
 
* [HTTPCLIENT-643] Automatic connect fail-over for multi-home remote servers.
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* [HTTPCLIENT-735] unsetting of DEFAULT_PROXY and FORCED_ROUTE in hierarchies
Contributed by Roland Weber <rolandw at apache.org>
 
* [HTTPCLIENT-723] route planner based on java.net.ProxySelector
Contributed by Roland Weber <rolandw at apache.org>
 
* [HTTPCLIENT-740] don't start connection GC thread in pool constructor
Contributed by Roland Weber <rolandw at apache.org>
 
* [HTTPCLIENT-736] route planners use SchemeRegistry instead of ConnManager
Contributed by Roland Weber <rolandw at apache.org>
 
* [HTTPCLIENT-730] Fixed rewriting of URIs containing escaped characters
Contributed by Sam Berlin <sberlin at gmail.com> and
Oleg Kalnichevski <olegk at apache.org>
* [HTTPCLIENT-667] Added 'Meta' cookie policy that selects a cookie
specification depending on the format of the cookie(s).
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* [HTTPCLIENT-729] Move HttpRoute and related classes to routing package.
Contributed by Roland Weber <rolandw at apache.org>
 
* [HTTPCLIENT-725] Use TimeUnit arguments for timeouts in connection manager.
Contributed by Roland Weber <rolandw at apache.org>
 
* [HTTPCLIENT-677] Connection manager no longer uses Thread.interrupt().
Contributed by Roland Weber <rolandw at apache.org>
 
* [HTTPCLIENT-716] Allow application-defined routes.
Contributed by Roland Weber <rolandw at apache.org>
 
* [HTTPCLIENT-712] Improve HttpRoute API
Contributed by Roland Weber <rolandw at apache.org>
 
* [HTTPCLIENT-711] Bad route computed for redirected requests
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* [HTTPCLIENT-715] Remove RoutedRequest from API
Contributed by Roland Weber <rolandw at apache.org>
 
* [HTTPCLIENT-705] Fixed incorrect handling of URIs with null path component.
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* [HTTPCLIENT-688] HttpOptions#getAllowedMethods can now handle multiple
Allow headers.
Contributed by Andrea Selva <selva.andre at gmail.com>
 
--------------------------------------
 
Release 4.0 Alpha 2
-------------------
 
ALPHA2 release is another milestone in the redesign of HttpClient. It includes
a number of improvements since ALPHA1, among which are improved connection
pooling, support for proxy chains, redesigned HTTP state and authentication
credentials management API, improved RFC 2965 cookie specification.
 
-------------------
 
HttpClient 3.x features that have NOT yet been ported
-------------------
* NTLM authentication scheme
 
* Support for multipart MIME coded entities
 
-------------------
 
Changelog
-------------------
 
* [HTTPCLIENT-698] Resolve non-absolute redirect URIs relative to
the request URI
Contributed by Johannes Koch <johannes.koch at fit.fraunhofer.de>
 
* [HTTPCLIENT-697] Throw a more intelligible exception when connection
to a remote host cannot be established.
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* [HTTPCLIENT-689] Caching of SimpleDateFormat in DateUtils
Contributed by Daniel Müller <strider at digitalstrider.com>
 
* [HTTPCLIENT-689] stackable parameters in AbstractHttpClient
Contributed by Roland Weber <rolandw at apache.org>
 
* [HTTPCLIENT-477] Use distinct instances of the authentication handler
interface for authentication with target and proxy hosts
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* [HTTPCLIENT-690] ManagedClientConnection provides access to SSLSession
Contributed by Roland Weber <rolandw at apache.org>
 
* [HTTPCLIENT-692] ClientConnectionManager throws InterruptedException
Contributed by Roland Weber <rolandw at apache.org>
 
* [HTTPCORE-116] moved parameter names to interfaces
Contributed by Roland Weber <rolandw at apache.org>
 
* [HTTPCLIENT-649] support for proxy chains in HttpConn
Contributed by Roland Weber <rolandw at apache.org>
 
* [HTTPCLIENT-636] refactor ThreadSafeClientConnManager in separate package
Contributed by Roland Weber <rolandw at apache.org>
 
* [HTTPCLIENT-669] new HttpRoutePlanner interface and implementation
Contributed by Andrea Selva <selva.andre at gmail.com>
 
* [HTTPCLIENT-653] detached connection wrapper no longer prevents
garbage collection of ThreadSafeClientConnManager
Contributed by Roland Weber <rolandw at apache.org>
 
* [HTTPCLIENT-674] use org.apache.http.util.VersionInfo instead of a local one
Contributed by Roland Weber <rolandw at apache.org>
 
* [HTTPCLIENT-666] Replaced HttpState with CredentialsProvier and CookieStore interfaces
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* [HTTPCORE-100] revised HttpContext hierarchy
Contributed by Roland Weber <rolandw at apache.org>
 
* [HTTPCLIENT-618] eliminate class HostConfiguration
Contributed by Roland Weber <rolandw at apache.org>
 
* [HTTPCLIENT-672] re-sync with API changes in core alpha6-SNAPSHOT
Contributed by Roland Weber <rolandw at apache.org>
 
--------------------------------------
 
Release 4.0 Alpha 1
-------------------
 
HttpClient 4.0 represents a complete, ground-up redesign and almost a complete
rewrite of the HttpClient 3.x codeline. This release finally addresses several
design flaws that existed since the 1.0 release and could not be fixed without
a major code overhaul and breaking API compatibility.
 
The HttpClient 4.0 API is still very experimental and is bound to change
during the course of the ALPHA development phase. Several important features
have not yet been ported to the new API.
 
Architectural changes
---------------------
 
* Redesign of the HttpClient internals addressing all known
major architectural shortcomings of the 3.x codeline
 
* Cleaner, more flexible and expressive API
 
* Better performance and smaller memory footprint due to a more
efficient HTTP transport based on HttpCore. HttpClient 4.0 is
expected to be 10% to 25% faster than HttpClient 3.x codeline
 
* More modular structure
 
* Pluggable redirect and authentication handlers
 
* Support for protocol incerceptors
 
* Improved connection management
 
* Improved support for sending requests via a proxy or a chain of
proxies
 
* Improved handling redirects of entity enclosing requests
 
* More flexible SSL context customization
 
* Reduced intermediate garbage in the process of
generating HTTP requests and parsing HTTP responses
 
-------------------
 
HttpClient 3.x features that have NOT yet been ported
-------------------
* NTLM authentication scheme
 
* RFC2965 cookie policy (Cookie2)
 
* Support for multipart MIME coded entities
 
-------------------
 
Changelog
-------------------
 
The following is a list of contributions tracked in JIRA.
Note that this is not a complete list of contributions or changes.
Since the API was redesigned completely, tracking everything outside
of the source code repository would have been too burdensome.
 
* [HTTPCLIENT-655] User-Agent string no longer violates RFC
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* [HTTPCLIENT-541] Virtual host API redesign
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* [HTTPCLIENT-614] Allow for different strategies when checking
CN of x509 certificates
Contributed by Julius Davies <juliusdavies at gmail.com>
 
* [HTTPCLIENT-136] Fixed inadequate proxy support
Long standing architectural problem. Issue opened on 19/Dec/2002.
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* [HTTPCLIENT-63] Support for pluggable redirect and authentication handlers
Long standing architectural problem. Issue opened on 15/Jul/2002.
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* [HTTPCLIENT-245] Fixed redirect handling. HttpClient can now automatically
handle redirects of entity enclosing requests.
Long standing architectural problem. Issue opened on 14/Jul/2003.
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* [HTTPCLIENT-613] HTTPS connections now verify CN of x509 certificates
Contributed by Julius Davies <juliusdavies at gmail.com>
 
* [HTTPCLIENT-497] Wire/header logger names consistent with class loggers
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* [HTTPCLIENT-484] AuthSSLProtocolSocketFactory in the main distribution
Contributed by Oleg Kalnichevski <olegk at apache.org>
 
* [HTTPCLIENT-589] Do not consume the remaining response content if
the connection is to be closed
Contributed by Roland Weber <rolandw at apache.org>
 
* [HTTPCLIENT-475] Support for unconnected sockets. HTTP requests can now be
aborted while network socket is still being connected.
Contributed by Roland Weber <rolandw at apache.org>
 
/ViaThinkSoft Java Utils/lib/httpcomponents-client-4.0.1/README.txt
0,0 → 1,78
Apache HttpComponents Client
============================
 
Welcome to the HttpClient component of the Apache HttpComponents project.
 
Building Instructions
---------------------
 
For building from source instructions please refer to BUILDING.txt.
 
Dependencies
------------
 
HttpClient main module requires Java 5.0 compatible runtime and
depends on the following external libraries:
 
* Apache HttpComponents HttpCore
* Apache Commons Logging
* Apache Commons Codec
 
(for detailed information on external dependencies please see pom.xml)
 
HttpMime module is optional and requires Java 5.0 compatible runtime
and depends on the following external libraries:
 
* Apache HttpComponents HttpCore
* Apache mime4j
* Apache Commons Logging
 
(for detailed information on external dependencies please see pom.xml)
 
Licensing
---------
 
Apache HttpComponents Client is licensed under the Apache License 2.0.
See the files called LICENSE.txt and NOTICE.txt for more information.
 
Cryptographic Software Notice
-----------------------------
 
This distribution may include software that has been designed for use
with cryptographic software. The country in which you currently reside
may have restrictions on the import, possession, use, and/or re-export
to another country, of encryption software. BEFORE using any encryption
software, please check your country's laws, regulations and policies
concerning the import, possession, or use, and re-export of encryption
software, to see if this is permitted. See <http://www.wassenaar.org/>
for more information.
 
The U.S. Government Department of Commerce, Bureau of Industry and
Security (BIS), has classified this software as Export Commodity
Control Number (ECCN) 5D002.C.1, which includes information security
software using or performing cryptographic functions with asymmetric
algorithms. The form and manner of this Apache Software Foundation
distribution makes it eligible for export under the License Exception
ENC Technology Software Unrestricted (TSU) exception (see the BIS
Export Administration Regulations, Section 740.13) for both object
code and source code.
 
The following provides more details on the included software that
may be subject to export controls on cryptographic software:
 
Apache HttpComponents Client interfaces with the
Java Secure Socket Extension (JSSE) API to provide
 
- HTTPS support
 
Apache HttpComponents Client does not include any
implementation of JSSE.
 
Contact
-------
 
o For general information visit the main project site at
http://hc.apache.org/
 
o For current status information visit the status page at
http://hc.apache.org/status.html
/ViaThinkSoft Java Utils/lib/httpcomponents-client-4.0.1/examples/org/apache/http/examples/entity/mime/ClientMultipartFormPost.java
0,0 → 1,79
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
 
package org.apache.http.examples.entity.mime;
 
import java.io.File;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
 
/**
* Example how to use multipart/form encoded POST request.
*/
public class ClientMultipartFormPost {
 
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.out.println("File path not given");
System.exit(1);
}
HttpClient httpclient = new DefaultHttpClient();
 
HttpPost httppost = new HttpPost("http://localhost:8080" +
"/servlets-examples/servlet/RequestInfoExample");
 
FileBody bin = new FileBody(new File(args[0]));
StringBody comment = new StringBody("A binary file of some kind");
 
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("bin", bin);
reqEntity.addPart("comment", comment);
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
 
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
System.out.println("Chunked?: " + resEntity.isChunked());
}
if (resEntity != null) {
resEntity.consumeContent();
}
}
}
/ViaThinkSoft Java Utils/lib/httpcomponents-client-4.0.1/examples/org/apache/http/examples/conn/ManagerConnectDirect.java
0,0 → 1,212
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
 
package org.apache.http.examples.conn;
 
 
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.scheme.SocketFactory;
import org.apache.http.conn.ClientConnectionRequest;
import org.apache.http.conn.ManagedClientConnection;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.BasicHttpContext;
 
 
 
/**
* How to open a direct connection using
* {@link ClientConnectionManager ClientConnectionManager}.
* This exemplifies the <i>opening</i> of the connection only.
* The subsequent message exchange in this example should not
* be used as a template.
*
*
*
* @since 4.0
*/
public class ManagerConnectDirect {
 
/**
* The default parameters.
* Instantiated in {@link #setup setup}.
*/
private static HttpParams defaultParameters = null;
 
/**
* The scheme registry.
* Instantiated in {@link #setup setup}.
*/
private static SchemeRegistry supportedSchemes;
 
 
/**
* Main entry point to this example.
*
* @param args ignored
*/
public final static void main(String[] args)
throws Exception {
 
final HttpHost target = new HttpHost("jakarta.apache.org", 80, "http");
 
setup(); // some general setup
 
ClientConnectionManager clcm = createManager();
 
HttpRequest req = createRequest(target);
HttpContext ctx = createContext();
 
System.out.println("preparing route to " + target);
HttpRoute route = new HttpRoute
(target, null, supportedSchemes.getScheme(target).isLayered());
 
System.out.println("requesting connection for " + route);
ClientConnectionRequest connRequest = clcm.requestConnection(route, null);
ManagedClientConnection conn = connRequest.getConnection(0, null);
try {
System.out.println("opening connection");
conn.open(route, ctx, getParams());
 
System.out.println("sending request");
conn.sendRequestHeader(req);
// there is no request entity
conn.flush();
 
System.out.println("receiving response header");
HttpResponse rsp = conn.receiveResponseHeader();
 
System.out.println("----------------------------------------");
System.out.println(rsp.getStatusLine());
Header[] headers = rsp.getAllHeaders();
for (int i=0; i<headers.length; i++) {
System.out.println(headers[i]);
}
System.out.println("----------------------------------------");
 
System.out.println("closing connection");
conn.close();
 
} finally {
 
if (conn.isOpen()) {
System.out.println("shutting down connection");
try {
conn.shutdown();
} catch (Exception x) {
System.out.println("problem during shutdown");
x.printStackTrace(System.out);
}
}
 
System.out.println("releasing connection");
clcm.releaseConnection(conn, -1, null);
}
 
} // main
 
 
private final static ClientConnectionManager createManager() {
 
return new ThreadSafeClientConnManager(getParams(), supportedSchemes);
}
 
 
/**
* Performs general setup.
* This should be called only once.
*/
private final static void setup() {
 
// Register the "http" protocol scheme, it is required
// by the default operator to look up socket factories.
supportedSchemes = new SchemeRegistry();
SocketFactory sf = PlainSocketFactory.getSocketFactory();
supportedSchemes.register(new Scheme("http", sf, 80));
 
// Prepare parameters.
// Since this example doesn't use the full core framework,
// only few parameters are actually required.
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setUseExpectContinue(params, false);
defaultParameters = params;
 
} // setup
 
 
private final static HttpParams getParams() {
return defaultParameters;
}
 
 
/**
* Creates a request to execute in this example.
* In a real application, request interceptors should be used
* to add the required headers.
*
* @param target the target server for the request
*
* @return a request without an entity
*/
private final static HttpRequest createRequest(HttpHost target) {
 
HttpRequest req = new BasicHttpRequest
("OPTIONS", "*", HttpVersion.HTTP_1_1);
 
req.addHeader("Host", target.getHostName());
 
return req;
}
 
 
/**
* Creates a context for executing a request.
* Since this example doesn't really use the execution framework,
* the context can be left empty.
*
* @return a new, empty context
*/
private final static HttpContext createContext() {
return new BasicHttpContext(null);
}
 
} // class ManagerConnectDirect
 
/ViaThinkSoft Java Utils/lib/httpcomponents-client-4.0.1/examples/org/apache/http/examples/conn/OperatorConnectDirect.java
0,0 → 1,112
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
 
package org.apache.http.examples.conn;
 
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.conn.ClientConnectionOperator;
import org.apache.http.conn.OperatedClientConnection;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.scheme.SocketFactory;
import org.apache.http.impl.conn.DefaultClientConnectionOperator;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.BasicHttpContext;
 
 
/**
* How to open a direct connection using
* {@link ClientConnectionOperator ClientConnectionOperator}.
* This exemplifies the <i>opening</i> of the connection only.
* The subsequent message exchange in this example should not
* be used as a template.
*
* @since 4.0
*/
public class OperatorConnectDirect {
 
public static void main(String[] args) throws Exception {
HttpHost target = new HttpHost("jakarta.apache.org", 80, "http");
 
// some general setup
// Register the "http" protocol scheme, it is required
// by the default operator to look up socket factories.
SchemeRegistry supportedSchemes = new SchemeRegistry();
SocketFactory sf = PlainSocketFactory.getSocketFactory();
supportedSchemes.register(new Scheme("http", sf, 80));
 
// Prepare parameters.
// Since this example doesn't use the full core framework,
// only few parameters are actually required.
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setUseExpectContinue(params, false);
 
// one operator can be used for many connections
ClientConnectionOperator scop = new DefaultClientConnectionOperator(supportedSchemes);
 
HttpRequest req = new BasicHttpRequest("OPTIONS", "*", HttpVersion.HTTP_1_1);
req.addHeader("Host", target.getHostName());
HttpContext ctx = new BasicHttpContext();
 
OperatedClientConnection conn = scop.createConnection();
try {
System.out.println("opening connection to " + target);
scop.openConnection(conn, target, null, ctx, params);
System.out.println("sending request");
conn.sendRequestHeader(req);
// there is no request entity
conn.flush();
 
System.out.println("receiving response header");
HttpResponse rsp = conn.receiveResponseHeader();
 
System.out.println("----------------------------------------");
System.out.println(rsp.getStatusLine());
Header[] headers = rsp.getAllHeaders();
for (int i = 0; i < headers.length; i++) {
System.out.println(headers[i]);
}
System.out.println("----------------------------------------");
} finally {
System.out.println("closing connection");
conn.close();
}
}
 
}
 
/ViaThinkSoft Java Utils/lib/httpcomponents-client-4.0.1/examples/org/apache/http/examples/conn/ManagerConnectProxy.java
0,0 → 1,275
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
 
package org.apache.http.examples.conn;
 
 
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.ClientConnectionRequest;
import org.apache.http.conn.ManagedClientConnection;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.scheme.SocketFactory;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.BasicHttpContext;
 
 
 
/**
* How to open a secure connection through a proxy using
* {@link ClientConnectionManager ClientConnectionManager}.
* This exemplifies the <i>opening</i> of the connection only.
* The message exchange, both subsequently and for tunnelling,
* should not be used as a template.
*
*
*
* @since 4.0
*/
public class ManagerConnectProxy {
 
/**
* The default parameters.
* Instantiated in {@link #setup setup}.
*/
private static HttpParams defaultParameters = null;
 
/**
* The scheme registry.
* Instantiated in {@link #setup setup}.
*/
private static SchemeRegistry supportedSchemes;
 
 
/**
* Main entry point to this example.
*
* @param args ignored
*/
public final static void main(String[] args)
throws Exception {
 
// make sure to use a proxy that supports CONNECT
final HttpHost target =
new HttpHost("issues.apache.org", 443, "https");
final HttpHost proxy =
new HttpHost("127.0.0.1", 8666, "http");
 
setup(); // some general setup
 
ClientConnectionManager clcm = createManager();
 
HttpRequest req = createRequest(target);
HttpContext ctx = createContext();
 
System.out.println("preparing route to " + target + " via " + proxy);
HttpRoute route = new HttpRoute
(target, null, proxy,
supportedSchemes.getScheme(target).isLayered());
 
System.out.println("requesting connection for " + route);
ClientConnectionRequest connRequest = clcm.requestConnection(route, null);
ManagedClientConnection conn = connRequest.getConnection(0, null);
try {
System.out.println("opening connection");
conn.open(route, ctx, getParams());
 
HttpRequest connect = createConnect(target);
System.out.println("opening tunnel to " + target);
conn.sendRequestHeader(connect);
// there is no request entity
conn.flush();
 
System.out.println("receiving confirmation for tunnel");
HttpResponse connected = conn.receiveResponseHeader();
System.out.println("----------------------------------------");
printResponseHeader(connected);
System.out.println("----------------------------------------");
int status = connected.getStatusLine().getStatusCode();
if ((status < 200) || (status > 299)) {
System.out.println("unexpected status code " + status);
System.exit(1);
}
System.out.println("receiving response body (ignored)");
conn.receiveResponseEntity(connected);
 
conn.tunnelTarget(false, getParams());
 
System.out.println("layering secure connection");
conn.layerProtocol(ctx, getParams());
 
// finally we have the secure connection and can send the request
 
System.out.println("sending request");
conn.sendRequestHeader(req);
// there is no request entity
conn.flush();
 
System.out.println("receiving response header");
HttpResponse rsp = conn.receiveResponseHeader();
 
System.out.println("----------------------------------------");
printResponseHeader(rsp);
System.out.println("----------------------------------------");
 
System.out.println("closing connection");
conn.close();
 
} finally {
 
if (conn.isOpen()) {
System.out.println("shutting down connection");
try {
conn.shutdown();
} catch (Exception x) {
System.out.println("problem during shutdown");
x.printStackTrace(System.out);
}
}
 
System.out.println("releasing connection");
clcm.releaseConnection(conn, -1, null);
}
 
} // main
 
 
private final static ClientConnectionManager createManager() {
 
return new ThreadSafeClientConnManager(getParams(), supportedSchemes);
}
 
 
/**
* Performs general setup.
* This should be called only once.
*/
private final static void setup() {
 
// Register the "http" and "https" protocol schemes, they are
// required by the default operator to look up socket factories.
supportedSchemes = new SchemeRegistry();
SocketFactory sf = PlainSocketFactory.getSocketFactory();
supportedSchemes.register(new Scheme("http", sf, 80));
sf = SSLSocketFactory.getSocketFactory();
supportedSchemes.register(new Scheme("https", sf, 80));
 
// Prepare parameters.
// Since this example doesn't use the full core framework,
// only few parameters are actually required.
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setUseExpectContinue(params, false);
defaultParameters = params;
 
} // setup
 
 
private final static HttpParams getParams() {
return defaultParameters;
}
 
 
/**
* Creates a request to tunnel a connection.
* In a real application, request interceptors should be used
* to add the required headers.
*
* @param target the target server for the tunnel
*
* @return a CONNECT request without an entity
*/
private final static HttpRequest createConnect(HttpHost target) {
 
// see RFC 2817, section 5.2
final String authority = target.getHostName()+":"+target.getPort();
 
HttpRequest req = new BasicHttpRequest
("CONNECT", authority, HttpVersion.HTTP_1_1);
 
req.addHeader("Host", authority);
 
return req;
}
 
 
/**
* Creates a request to execute in this example.
* In a real application, request interceptors should be used
* to add the required headers.
*
* @param target the target server for the request
*
* @return a request without an entity
*/
private final static HttpRequest createRequest(HttpHost target) {
 
HttpRequest req = new BasicHttpRequest
("OPTIONS", "*", HttpVersion.HTTP_1_1);
 
req.addHeader("Host", target.getHostName());
 
return req;
}
 
 
/**
* Creates a context for executing a request.
* Since this example doesn't really use the execution framework,
* the context can be left empty.
*
* @return a new, empty context
*/
private final static HttpContext createContext() {
return new BasicHttpContext(null);
}
 
 
private final static void printResponseHeader(HttpResponse rsp) {
 
System.out.println(rsp.getStatusLine());
Header[] headers = rsp.getAllHeaders();
for (int i=0; i<headers.length; i++) {
System.out.println(headers[i]);
}
}
 
} // class ManagerConnectProxy
 
/ViaThinkSoft Java Utils/lib/httpcomponents-client-4.0.1/examples/org/apache/http/examples/conn/OperatorConnectProxy.java
0,0 → 1,163
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
 
package org.apache.http.examples.conn;
 
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.conn.ClientConnectionOperator;
import org.apache.http.conn.OperatedClientConnection;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.conn.DefaultClientConnectionOperator;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.BasicHttpContext;
 
/**
* How to open a secure connection through a proxy using
* {@link ClientConnectionOperator ClientConnectionOperator}.
* This exemplifies the <i>opening</i> of the connection only.
* The message exchange, both subsequently and for tunnelling,
* should not be used as a template.
*
* @since 4.0
*/
public class OperatorConnectProxy {
 
public static void main(String[] args) throws Exception {
 
// make sure to use a proxy that supports CONNECT
HttpHost target = new HttpHost("issues.apache.org", 443, "https");
HttpHost proxy = new HttpHost("127.0.0.1", 8666, "http");
 
// some general setup
// Register the "http" and "https" protocol schemes, they are
// required by the default operator to look up socket factories.
SchemeRegistry supportedSchemes = new SchemeRegistry();
supportedSchemes.register(new Scheme("http",
PlainSocketFactory.getSocketFactory(), 80));
supportedSchemes.register(new Scheme("https",
SSLSocketFactory.getSocketFactory(), 443));
 
// Prepare parameters.
// Since this example doesn't use the full core framework,
// only few parameters are actually required.
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setUseExpectContinue(params, false);
 
// one operator can be used for many connections
ClientConnectionOperator scop = new DefaultClientConnectionOperator(supportedSchemes);
 
HttpRequest req = new BasicHttpRequest("OPTIONS", "*", HttpVersion.HTTP_1_1);
// In a real application, request interceptors should be used
// to add the required headers.
req.addHeader("Host", target.getHostName());
HttpContext ctx = new BasicHttpContext();
 
OperatedClientConnection conn = scop.createConnection();
try {
System.out.println("opening connection to " + proxy);
scop.openConnection(conn, proxy, null, ctx, params);
 
// Creates a request to tunnel a connection.
// For details see RFC 2817, section 5.2
String authority = target.getHostName() + ":" + target.getPort();
HttpRequest connect = new BasicHttpRequest("CONNECT", authority,
HttpVersion.HTTP_1_1);
// In a real application, request interceptors should be used
// to add the required headers.
connect.addHeader("Host", authority);
 
System.out.println("opening tunnel to " + target);
conn.sendRequestHeader(connect);
// there is no request entity
conn.flush();
 
System.out.println("receiving confirmation for tunnel");
HttpResponse connected = conn.receiveResponseHeader();
System.out.println("----------------------------------------");
printResponseHeader(connected);
System.out.println("----------------------------------------");
int status = connected.getStatusLine().getStatusCode();
if ((status < 200) || (status > 299)) {
System.out.println("unexpected status code " + status);
System.exit(1);
}
System.out.println("receiving response body (ignored)");
conn.receiveResponseEntity(connected);
 
// Now we have a tunnel to the target. As we will be creating a
// layered TLS/SSL socket immediately afterwards, updating the
// connection with the new target is optional - but good style.
// The scheme part of the target is already "https", though the
// connection is not yet switched to the TLS/SSL protocol.
conn.update(null, target, false, params);
 
System.out.println("layering secure connection");
scop.updateSecureConnection(conn, target, ctx, params);
 
// finally we have the secure connection and can send the request
 
System.out.println("sending request");
conn.sendRequestHeader(req);
// there is no request entity
conn.flush();
 
System.out.println("receiving response header");
HttpResponse rsp = conn.receiveResponseHeader();
 
System.out.println("----------------------------------------");
printResponseHeader(rsp);
System.out.println("----------------------------------------");
 
} finally {
System.out.println("closing connection");
conn.close();
}
}
 
private final static void printResponseHeader(HttpResponse rsp) {
System.out.println(rsp.getStatusLine());
Header[] headers = rsp.getAllHeaders();
for (int i=0; i<headers.length; i++) {
System.out.println(headers[i]);
}
}
 
}
 
/ViaThinkSoft Java Utils/lib/httpcomponents-client-4.0.1/examples/org/apache/http/examples/client/ClientChunkEncodedPost.java
0,0 → 1,88
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
 
package org.apache.http.examples.client;
 
import java.io.File;
import java.io.FileInputStream;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.DefaultHttpClient;
 
/**
* Example how to use unbuffered chunk-encoded POST request.
*/
public class ClientChunkEncodedPost {
 
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.out.println("File path not given");
System.exit(1);
}
HttpClient httpclient = new DefaultHttpClient();
 
HttpPost httppost = new HttpPost("http://localhost:8080" +
"/servlets-examples/servlet/RequestInfoExample");
 
File file = new File(args[0]);
 
InputStreamEntity reqEntity = new InputStreamEntity(
new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true);
// It may be more appropriate to use FileEntity class in this particular
// instance but we are using a more generic InputStreamEntity to demonstrate
// the capability to stream out data from any arbitrary source
//
// FileEntity entity = new FileEntity(file, "binary/octet-stream");
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
 
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
System.out.println("Chunked?: " + resEntity.isChunked());
}
if (resEntity != null) {
resEntity.consumeContent();
}
 
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
/ViaThinkSoft Java Utils/lib/httpcomponents-client-4.0.1/examples/org/apache/http/examples/client/ClientConnectionRelease.java
0,0 → 1,101
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
 
package org.apache.http.examples.client;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
 
/**
* This example demonstrates the recommended way of using API to make sure
* the underlying connection gets released back to the connection manager.
*/
public class ClientConnectionRelease {
 
public final static void main(String[] args) throws Exception {
HttpClient httpclient = new DefaultHttpClient();
 
HttpGet httpget = new HttpGet("http://www.apache.org/");
 
// Execute HTTP request
System.out.println("executing request " + httpget.getURI());
HttpResponse response = httpclient.execute(httpget);
 
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
System.out.println("----------------------------------------");
 
// Get hold of the response entity
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to bother about connection release
if (entity != null) {
BufferedReader reader = new BufferedReader(
new InputStreamReader(entity.getContent()));
try {
// do something useful with the response
System.out.println(reader.readLine());
} catch (IOException ex) {
 
// In case of an IOException the connection will be released
// back to the connection manager automatically
throw ex;
} catch (RuntimeException ex) {
 
// In case of an unexpected exception you may want to abort
// the HTTP request in order to shut down the underlying
// connection and release it back to the connection manager.
httpget.abort();
throw ex;
} finally {
 
// Closing the input stream will trigger connection release
reader.close();
}
}
 
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
 
}
 
/ViaThinkSoft Java Utils/lib/httpcomponents-client-4.0.1/examples/org/apache/http/examples/client/ClientExecuteProxy.java
0,0 → 1,110
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
 
package org.apache.http.examples.client;
 
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;
 
/**
* How to send a request via proxy using {@link HttpClient}.
*
* @since 4.0
*/
public class ClientExecuteProxy {
 
public static void main(String[] args)throws Exception {
 
// make sure to use a proxy that supports CONNECT
HttpHost target = new HttpHost("issues.apache.org", 443, "https");
HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http");
 
// general setup
SchemeRegistry supportedSchemes = new SchemeRegistry();
 
// Register the "http" and "https" protocol schemes, they are
// required by the default operator to look up socket factories.
supportedSchemes.register(new Scheme("http",
PlainSocketFactory.getSocketFactory(), 80));
supportedSchemes.register(new Scheme("https",
SSLSocketFactory.getSocketFactory(), 443));
 
// prepare parameters
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
HttpProtocolParams.setUseExpectContinue(params, true);
 
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params,
supportedSchemes);
 
DefaultHttpClient httpclient = new DefaultHttpClient(ccm, params);
 
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
 
HttpGet req = new HttpGet("/");
 
System.out.println("executing request to " + target + " via " + proxy);
HttpResponse rsp = httpclient.execute(target, req);
HttpEntity entity = rsp.getEntity();
 
System.out.println("----------------------------------------");
System.out.println(rsp.getStatusLine());
Header[] headers = rsp.getAllHeaders();
for (int i = 0; i<headers.length; i++) {
System.out.println(headers[i]);
}
System.out.println("----------------------------------------");
 
if (entity != null) {
System.out.println(EntityUtils.toString(entity));
}
 
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
 
}
/ViaThinkSoft Java Utils/lib/httpcomponents-client-4.0.1/examples/org/apache/http/examples/client/ClientAbortMethod.java
0,0 → 1,68
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
 
package org.apache.http.examples.client;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
 
/**
* This example demonstrates how to abort an HTTP method before its normal completion.
*/
public class ClientAbortMethod {
 
public final static void main(String[] args) throws Exception {
HttpClient httpclient = new DefaultHttpClient();
 
HttpGet httpget = new HttpGet("http://www.apache.org/");
 
System.out.println("executing request " + httpget.getURI());
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
 
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
System.out.println("----------------------------------------");
 
// Do not feel like reading the response body
// Call abort on the request object
httpget.abort();
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
 
}
 
/ViaThinkSoft Java Utils/lib/httpcomponents-client-4.0.1/examples/org/apache/http/examples/client/ClientInteractiveAuthentication.java
0,0 → 1,119
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
 
package org.apache.http.examples.client;
 
import java.io.BufferedReader;
import java.io.InputStreamReader;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.AuthState;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
 
/**
* A simple example that uses HttpClient to execute an HTTP request against
* a target site that requires user authentication.
*/
public class ClientInteractiveAuthentication {
 
public static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
 
// Create local execution context
HttpContext localContext = new BasicHttpContext();
 
HttpGet httpget = new HttpGet("http://localhost/test");
boolean trying = true;
while (trying) {
System.out.println("executing request " + httpget.getRequestLine());
HttpResponse response = httpclient.execute(httpget, localContext);
 
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
 
// Consume response content
HttpEntity entity = response.getEntity();
if (entity != null) {
entity.consumeContent();
}
int sc = response.getStatusLine().getStatusCode();
AuthState authState = null;
if (sc == HttpStatus.SC_UNAUTHORIZED) {
// Target host authentication required
authState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE);
}
if (sc == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
// Proxy authentication required
authState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE);
}
if (authState != null) {
System.out.println("----------------------------------------");
AuthScope authScope = authState.getAuthScope();
System.out.println("Please provide credentials");
System.out.println(" Host: " + authScope.getHost() + ":" + authScope.getPort());
System.out.println(" Realm: " + authScope.getRealm());
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter username: ");
String user = console.readLine();
System.out.print("Enter password: ");
String password = console.readLine();
if (user != null && user.length() > 0) {
Credentials creds = new UsernamePasswordCredentials(user, password);
httpclient.getCredentialsProvider().setCredentials(authScope, creds);
trying = true;
} else {
trying = false;
}
} else {
trying = false;
}
}
 
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
/ViaThinkSoft Java Utils/lib/httpcomponents-client-4.0.1/examples/org/apache/http/examples/client/ClientAuthentication.java
0,0 → 1,71
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
 
package org.apache.http.examples.client;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
 
/**
* A simple example that uses HttpClient to execute an HTTP request against
* a target site that requires user authentication.
*/
public class ClientAuthentication {
 
public static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
 
httpclient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", 443),
new UsernamePasswordCredentials("username", "password"));
HttpGet httpget = new HttpGet("https://localhost/protected");
System.out.println("executing request" + httpget.getRequestLine());
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
 
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
if (entity != null) {
entity.consumeContent();
}
 
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
/ViaThinkSoft Java Utils/lib/httpcomponents-client-4.0.1/examples/org/apache/http/examples/client/ClientCustomContext.java
0,0 → 1,95
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
 
package org.apache.http.examples.client;
 
import java.util.List;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.BasicHttpContext;
 
 
/**
* This example demonstrates the use of a local HTTP context populated with
* custom attributes.
*/
public class ClientCustomContext {
 
public final static void main(String[] args) throws Exception {
HttpClient httpclient = new DefaultHttpClient();
 
// Create a local instance of cookie store
CookieStore cookieStore = new BasicCookieStore();
// Create local HTTP context
HttpContext localContext = new BasicHttpContext();
// Bind custom cookie store to the local context
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
HttpGet httpget = new HttpGet("http://www.google.com/");
 
System.out.println("executing request " + httpget.getURI());
 
// Pass local context as a parameter
HttpResponse response = httpclient.execute(httpget, localContext);
HttpEntity entity = response.getEntity();
 
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
List<Cookie> cookies = cookieStore.getCookies();
for (int i = 0; i < cookies.size(); i++) {
System.out.println("Local cookie: " + cookies.get(i));
}
// Consume response content
if (entity != null) {
entity.consumeContent();
}
System.out.println("----------------------------------------");
 
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
 
/ViaThinkSoft Java Utils/lib/httpcomponents-client-4.0.1/examples/org/apache/http/examples/client/ClientMultiThreadedExecution.java
0,0 → 1,148
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.examples.client;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.util.EntityUtils;
 
/**
* An example that performs GETs from multiple threads.
*
*/
public class ClientMultiThreadedExecution {
 
public static void main(String[] args) throws Exception {
// Create and initialize HTTP parameters
HttpParams params = new BasicHttpParams();
ConnManagerParams.setMaxTotalConnections(params, 100);
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
// Create and initialize scheme registry
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(
new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
// Create an HttpClient with the ThreadSafeClientConnManager.
// This connection manager must be used if more than one thread will
// be using the HttpClient.
ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
HttpClient httpClient = new DefaultHttpClient(cm, params);
// create an array of URIs to perform GETs on
String[] urisToGet = {
"http://hc.apache.org/",
"http://hc.apache.org/httpcomponents-core/",
"http://hc.apache.org/httpcomponents-client/",
"http://svn.apache.org/viewvc/httpcomponents/"
};
// create a thread for each URI
GetThread[] threads = new GetThread[urisToGet.length];
for (int i = 0; i < threads.length; i++) {
HttpGet httpget = new HttpGet(urisToGet[i]);
threads[i] = new GetThread(httpClient, httpget, i + 1);
}
// start the threads
for (int j = 0; j < threads.length; j++) {
threads[j].start();
}
// join the threads
for (int j = 0; j < threads.length; j++) {
threads[j].join();
}
 
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpClient.getConnectionManager().shutdown();
}
/**
* A thread that performs a GET.
*/
static class GetThread extends Thread {
private final HttpClient httpClient;
private final HttpContext context;
private final HttpGet httpget;
private final int id;
public GetThread(HttpClient httpClient, HttpGet httpget, int id) {
this.httpClient = httpClient;
this.context = new BasicHttpContext();
this.httpget = httpget;
this.id = id;
}
/**
* Executes the GetMethod and prints some status information.
*/
@Override
public void run() {
System.out.println(id + " - about to get something from " + httpget.getURI());
 
try {
// execute the method
HttpResponse response = httpClient.execute(httpget, context);
System.out.println(id + " - get executed");
// get the response body as an array of bytes
HttpEntity entity = response.getEntity();
if (entity != null) {
byte[] bytes = EntityUtils.toByteArray(entity);
System.out.println(id + " - " + bytes.length + " bytes read");
}
} catch (Exception e) {
httpget.abort();
System.out.println(id + " - error: " + e);
}
}
}
}
/ViaThinkSoft Java Utils/lib/httpcomponents-client-4.0.1/examples/org/apache/http/examples/client/ClientPreemptiveDigestAuthentication.java
0,0 → 1,165
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
 
package org.apache.http.examples.client;
 
import java.io.IOException;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.auth.AuthScheme;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.AuthState;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.auth.DigestScheme;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
 
/**
* An example of HttpClient can be customized to authenticate
* preemptively using DIGEST scheme.
* <b/>
* Generally, preemptive authentication can be considered less
* secure than a response to an authentication challenge
* and therefore discouraged.
* <b/>
* This code is NOT officially supported! Use at your risk.
*/
public class ClientPreemptiveDigestAuthentication {
 
public static void main(String[] args) throws Exception {
 
DefaultHttpClient httpclient = new DefaultHttpClient();
 
httpclient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", 80),
new UsernamePasswordCredentials("username", "password"));
 
BasicHttpContext localcontext = new BasicHttpContext();
// Generate DIGEST scheme object, initialize it and stick it to
// the local execution context
DigestScheme digestAuth = new DigestScheme();
// Suppose we already know the realm name
digestAuth.overrideParamter("realm", "some realm");
// Suppose we already know the expected nonce value
digestAuth.overrideParamter("nonce", "whatever");
localcontext.setAttribute("preemptive-auth", digestAuth);
// Add as the first request interceptor
httpclient.addRequestInterceptor(new PreemptiveAuth(), 0);
// Add as the last response interceptor
httpclient.addResponseInterceptor(new PersistentDigest());
HttpHost targetHost = new HttpHost("localhost", 80, "http");
 
HttpGet httpget = new HttpGet("/");
 
System.out.println("executing request: " + httpget.getRequestLine());
System.out.println("to target: " + targetHost);
for (int i = 0; i < 3; i++) {
HttpResponse response = httpclient.execute(targetHost, httpget, localcontext);
HttpEntity entity = response.getEntity();
 
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
entity.consumeContent();
}
}
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
static class PreemptiveAuth implements HttpRequestInterceptor {
 
public void process(
final HttpRequest request,
final HttpContext context) throws HttpException, IOException {
AuthState authState = (AuthState) context.getAttribute(
ClientContext.TARGET_AUTH_STATE);
// If no auth scheme avaialble yet, try to initialize it preemptively
if (authState.getAuthScheme() == null) {
AuthScheme authScheme = (AuthScheme) context.getAttribute(
"preemptive-auth");
CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(
ClientContext.CREDS_PROVIDER);
HttpHost targetHost = (HttpHost) context.getAttribute(
ExecutionContext.HTTP_TARGET_HOST);
if (authScheme != null) {
Credentials creds = credsProvider.getCredentials(
new AuthScope(
targetHost.getHostName(),
targetHost.getPort()));
if (creds == null) {
throw new HttpException("No credentials for preemptive authentication");
}
authState.setAuthScheme(authScheme);
authState.setCredentials(creds);
}
}
}
}
 
static class PersistentDigest implements HttpResponseInterceptor {
 
public void process(
final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
AuthState authState = (AuthState) context.getAttribute(
ClientContext.TARGET_AUTH_STATE);
if (authState != null) {
AuthScheme authScheme = authState.getAuthScheme();
// Stick the auth scheme to the local context, so
// we could try to authenticate subsequent requests
// preemptively
if (authScheme instanceof DigestScheme) {
context.setAttribute("preemptive-auth", authScheme);
}
}
}
}
}
/ViaThinkSoft Java Utils/lib/httpcomponents-client-4.0.1/examples/org/apache/http/examples/client/ClientProxyAuthentication.java
0,0 → 1,79
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
 
package org.apache.http.examples.client;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
 
/**
* A simple example that uses HttpClient to execute an HTTP request
* over a secure connection tunneled through an authenticating proxy.
*/
public class ClientProxyAuthentication {
 
public static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
 
httpclient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", 8080),
new UsernamePasswordCredentials("username", "password"));
 
HttpHost targetHost = new HttpHost("www.verisign.com", 443, "https");
HttpHost proxy = new HttpHost("localhost", 8080);
 
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
 
HttpGet httpget = new HttpGet("/");
System.out.println("executing request: " + httpget.getRequestLine());
System.out.println("via proxy: " + proxy);
System.out.println("to target: " + targetHost);
HttpResponse response = httpclient.execute(targetHost, httpget);
HttpEntity entity = response.getEntity();
 
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
if (entity != null) {
entity.consumeContent();
}
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
/ViaThinkSoft Java Utils/lib/httpcomponents-client-4.0.1/examples/org/apache/http/examples/client/ClientPreemptiveBasicAuthentication.java
0,0 → 1,138
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
 
package org.apache.http.examples.client;
 
import java.io.IOException;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScheme;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.AuthState;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
 
/**
* An example of HttpClient can be customized to authenticate
* preemptively using BASIC scheme.
* <b/>
* Generally, preemptive authentication can be considered less
* secure than a response to an authentication challenge
* and therefore discouraged.
* <b/>
* This code is NOT officially supported! Use at your risk.
*/
public class ClientPreemptiveBasicAuthentication {
 
public static void main(String[] args) throws Exception {
 
DefaultHttpClient httpclient = new DefaultHttpClient();
 
httpclient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", 80),
new UsernamePasswordCredentials("username", "password"));
 
BasicHttpContext localcontext = new BasicHttpContext();
 
// Generate BASIC scheme object and stick it to the local
// execution context
BasicScheme basicAuth = new BasicScheme();
localcontext.setAttribute("preemptive-auth", basicAuth);
// Add as the first request interceptor
httpclient.addRequestInterceptor(new PreemptiveAuth(), 0);
HttpHost targetHost = new HttpHost("localhost", 80, "http");
 
HttpGet httpget = new HttpGet("/");
 
System.out.println("executing request: " + httpget.getRequestLine());
System.out.println("to target: " + targetHost);
for (int i = 0; i < 3; i++) {
HttpResponse response = httpclient.execute(targetHost, httpget, localcontext);
HttpEntity entity = response.getEntity();
 
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
entity.consumeContent();
}
}
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
static class PreemptiveAuth implements HttpRequestInterceptor {
 
public void process(
final HttpRequest request,
final HttpContext context) throws HttpException, IOException {
AuthState authState = (AuthState) context.getAttribute(
ClientContext.TARGET_AUTH_STATE);
// If no auth scheme avaialble yet, try to initialize it preemptively
if (authState.getAuthScheme() == null) {
AuthScheme authScheme = (AuthScheme) context.getAttribute(
"preemptive-auth");
CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(
ClientContext.CREDS_PROVIDER);
HttpHost targetHost = (HttpHost) context.getAttribute(
ExecutionContext.HTTP_TARGET_HOST);
if (authScheme != null) {
Credentials creds = credsProvider.getCredentials(
new AuthScope(
targetHost.getHostName(),
targetHost.getPort()));
if (creds == null) {
throw new HttpException("No credentials for preemptive authentication");
}
authState.setAuthScheme(authScheme);
authState.setCredentials(creds);
}
}
}
}
}
/ViaThinkSoft Java Utils/lib/httpcomponents-client-4.0.1/examples/org/apache/http/examples/client/ClientGZipContentCompression.java
0,0 → 1,151
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
 
package org.apache.http.examples.client;
 
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
 
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
 
/**
* Demonstration of the use of protocol interceptors to transparently
* modify properties of HTTP messages sent / received by the HTTP client.
* <p/>
* In this particular case HTTP client is made capable of transparent content
* GZIP compression by adding two protocol interceptors: a request interceptor
* that adds 'Accept-Encoding: gzip' header to all outgoing requests and
* a response interceptor that automatically expands compressed response
* entities by wrapping them with a uncompressing decorator class. The use of
* protocol interceptors makes content compression completely transparent to
* the consumer of the {@link org.apache.http.client.HttpClient HttpClient}
* interface.
*/
public class ClientGZipContentCompression {
 
public final static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
 
httpclient.addRequestInterceptor(new HttpRequestInterceptor() {
public void process(
final HttpRequest request,
final HttpContext context) throws HttpException, IOException {
if (!request.containsHeader("Accept-Encoding")) {
request.addHeader("Accept-Encoding", "gzip");
}
}
 
});
httpclient.addResponseInterceptor(new HttpResponseInterceptor() {
public void process(
final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
HttpEntity entity = response.getEntity();
Header ceheader = entity.getContentEncoding();
if (ceheader != null) {
HeaderElement[] codecs = ceheader.getElements();
for (int i = 0; i < codecs.length; i++) {
if (codecs[i].getName().equalsIgnoreCase("gzip")) {
response.setEntity(
new GzipDecompressingEntity(response.getEntity()));
return;
}
}
}
}
});
HttpGet httpget = new HttpGet("http://www.apache.org/");
// Execute HTTP request
System.out.println("executing request " + httpget.getURI());
HttpResponse response = httpclient.execute(httpget);
 
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
System.out.println(response.getLastHeader("Content-Encoding"));
System.out.println(response.getLastHeader("Content-Length"));
System.out.println("----------------------------------------");
 
HttpEntity entity = response.getEntity();
if (entity != null) {
String content = EntityUtils.toString(entity);
System.out.println(content);
System.out.println("----------------------------------------");
System.out.println("Uncompressed size: "+content.length());
}
 
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
 
static class GzipDecompressingEntity extends HttpEntityWrapper {
 
public GzipDecompressingEntity(final HttpEntity entity) {
super(entity);
}
@Override
public InputStream getContent()
throws IOException, IllegalStateException {
 
// the wrapped entity's getContent() decides about repeatability
InputStream wrappedin = wrappedEntity.getContent();
 
return new GZIPInputStream(wrappedin);
}
 
@Override
public long getContentLength() {
// length of ungzipped content is not known
return -1;
}
 
}
}
 
/ViaThinkSoft Java Utils/lib/httpcomponents-client-4.0.1/examples/org/apache/http/examples/client/ClientWithResponseHandler.java
0,0 → 1,64
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
 
package org.apache.http.examples.client;
 
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
 
/**
* This example demonstrates the use of the {@link ResponseHandler} to simplify
* the process of processing the HTTP response and releasing associated resources.
*/
public class ClientWithResponseHandler {
 
public final static void main(String[] args) throws Exception {
HttpClient httpclient = new DefaultHttpClient();
 
HttpGet httpget = new HttpGet("http://www.google.com/");
 
System.out.println("executing request " + httpget.getURI());
 
// Create a response handler
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httpget, responseHandler);
System.out.println(responseBody);
System.out.println("----------------------------------------");
 
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
 
/ViaThinkSoft Java Utils/lib/httpcomponents-client-4.0.1/examples/org/apache/http/examples/client/ClientCustomSSL.java
0,0 → 1,83
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
 
package org.apache.http.examples.client;
 
import java.io.File;
import java.io.FileInputStream;
import java.security.KeyStore;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
 
/**
* This example demonstrates how to create secure connections with a custom SSL
* context.
*/
public class ClientCustomSSL {
 
public final static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
 
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
FileInputStream instream = new FileInputStream(new File("my.keystore"));
try {
trustStore.load(instream, "nopassword".toCharArray());
} finally {
instream.close();
}
SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
Scheme sch = new Scheme("https", socketFactory, 443);
httpclient.getConnectionManager().getSchemeRegistry().register(sch);
 
HttpGet httpget = new HttpGet("https://localhost/");
 
System.out.println("executing request" + httpget.getRequestLine());
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
 
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
if (entity != null) {
entity.consumeContent();
}
 
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
 
}
/ViaThinkSoft Java Utils/lib/httpcomponents-client-4.0.1/examples/org/apache/http/examples/client/ClientFormLogin.java
0,0 → 1,105
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
 
package org.apache.http.examples.client;
 
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
 
/**
* A example that demonstrates how HttpClient APIs can be used to perform
* form-based logon.
*/
public class ClientFormLogin {
 
public static void main(String[] args) throws Exception {
 
DefaultHttpClient httpclient = new DefaultHttpClient();
 
HttpGet httpget = new HttpGet("https://portal.sun.com/portal/dt");
 
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
 
System.out.println("Login form get: " + response.getStatusLine());
if (entity != null) {
entity.consumeContent();
}
System.out.println("Initial set of cookies:");
List<Cookie> cookies = httpclient.getCookieStore().getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
}
}
 
HttpPost httpost = new HttpPost("https://portal.sun.com/amserver/UI/Login?" +
"org=self_registered_users&" +
"goto=/portal/dt&" +
"gotoOnFail=/portal/dt?error=true");
 
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("IDToken1", "username"));
nvps.add(new BasicNameValuePair("IDToken2", "password"));
 
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
 
response = httpclient.execute(httpost);
entity = response.getEntity();
 
System.out.println("Login form get: " + response.getStatusLine());
if (entity != null) {
entity.consumeContent();
}
 
System.out.println("Post logon cookies:");
cookies = httpclient.getCookieStore().getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
}
}
 
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
/ViaThinkSoft Java Utils/lib/httpcomponents-client-4.0.1/examples/org/apache/http/examples/client/ClientExecuteDirect.java
0,0 → 1,102
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
 
package org.apache.http.examples.client;
 
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;
 
/**
* How to send a request directly using {@link HttpClient}.
*
* @since 4.0
*/
public class ClientExecuteDirect {
 
public static void main(String[] args) throws Exception {
 
HttpHost target = new HttpHost("www.apache.org", 80, "http");
 
// general setup
SchemeRegistry supportedSchemes = new SchemeRegistry();
 
// Register the "http" protocol scheme, it is required
// by the default operator to look up socket factories.
supportedSchemes.register(new Scheme("http",
PlainSocketFactory.getSocketFactory(), 80));
 
// prepare parameters
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
HttpProtocolParams.setUseExpectContinue(params, true);
 
ClientConnectionManager connMgr = new ThreadSafeClientConnManager(params,
supportedSchemes);
DefaultHttpClient httpclient = new DefaultHttpClient(connMgr, params);
 
HttpGet req = new HttpGet("/");
 
System.out.println("executing request to " + target);
 
HttpResponse rsp = httpclient.execute(target, req);
HttpEntity entity = rsp.getEntity();
 
System.out.println("----------------------------------------");
System.out.println(rsp.getStatusLine());
Header[] headers = rsp.getAllHeaders();
for (int i = 0; i < headers.length; i++) {
System.out.println(headers[i]);
}
System.out.println("----------------------------------------");
 
if (entity != null) {
System.out.println(EntityUtils.toString(entity));
}
 
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
 
}
/ViaThinkSoft Java Utils/lib/httpcomponents-client-4.0.1/examples/org/apache/http/examples/client/ClientEvictExpiredConnections.java
0,0 → 1,150
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.examples.client;
 
import java.util.concurrent.TimeUnit;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
 
/**
* Example demonstrating how to evict expired and idle connections
* from the connection pool.
*/
public class ClientEvictExpiredConnections {
 
public static void main(String[] args) throws Exception {
// Create and initialize HTTP parameters
HttpParams params = new BasicHttpParams();
ConnManagerParams.setMaxTotalConnections(params, 100);
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
// Create and initialize scheme registry
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(
new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
HttpClient httpclient = new DefaultHttpClient(cm, params);
// create an array of URIs to perform GETs on
String[] urisToGet = {
"http://jakarta.apache.org/",
"http://jakarta.apache.org/commons/",
"http://jakarta.apache.org/commons/httpclient/",
"http://svn.apache.org/viewvc/jakarta/httpcomponents/"
};
IdleConnectionEvictor connEvictor = new IdleConnectionEvictor(cm);
connEvictor.start();
for (int i = 0; i < urisToGet.length; i++) {
String requestURI = urisToGet[i];
HttpGet req = new HttpGet(requestURI);
 
System.out.println("executing request " + requestURI);
 
HttpResponse rsp = httpclient.execute(req);
HttpEntity entity = rsp.getEntity();
 
System.out.println("----------------------------------------");
System.out.println(rsp.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
System.out.println("----------------------------------------");
 
if (entity != null) {
entity.consumeContent();
}
}
// Sleep 10 sec and let the connection evictor do its job
Thread.sleep(20000);
// Shut down the evictor thread
connEvictor.shutdown();
connEvictor.join();
 
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
public static class IdleConnectionEvictor extends Thread {
private final ClientConnectionManager connMgr;
private volatile boolean shutdown;
public IdleConnectionEvictor(ClientConnectionManager connMgr) {
super();
this.connMgr = connMgr;
}
 
@Override
public void run() {
try {
while (!shutdown) {
synchronized (this) {
wait(5000);
// Close expired connections
connMgr.closeExpiredConnections();
// Optionally, close connections
// that have been idle longer than 5 sec
connMgr.closeIdleConnections(5, TimeUnit.SECONDS);
}
}
} catch (InterruptedException ex) {
// terminate
}
}
public void shutdown() {
shutdown = true;
synchronized (this) {
notifyAll();
}
}
}
}
/ViaThinkSoft Java Utils/lib/javamail/activation.jar
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/ViaThinkSoft Java Utils/lib/javamail/mail.jar
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property