HttpComponents HttpClient: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
 
(6 intermediate revisions by the same user not shown)
Line 2: Line 2:


* http://hc.apache.org/httpcomponents-client-ga/
* http://hc.apache.org/httpcomponents-client-ga/
* tutorial http://hc.apache.org/httpcomponents-client-ga/tutorial/html/index.html
* [http://hc.apache.org/httpcomponents-client-ga/tutorial/html/index.html HttpClient Tutorial]


=Internal=
=Internal=
Line 8: Line 8:
* [[Apache Foundation#Subjects|Apache Foundation]]
* [[Apache Foundation#Subjects|Apache Foundation]]


=Overview=


!!!Primer
Simplest GET usage pattern:


!!!Simplest GET Usage Pattern
<pre>
...


{{{
HttpMethod method = new GetMethod("http://localhost:8080/");
        ...


        HttpMethod method = new GetMethod("http://localhost:8080/");
try {


        try
    int responseCode = httpClient.executeMethod(method);
        {
            int responseCode = httpClient.executeMethod(method);


            if (responseCode != HttpStatus.SC_OK)
    if (responseCode != HttpStatus.SC_OK) {
            {
                throw new Exception("HTTP invocation failed: " + method.getStatusLine());
            }


            byte[] body = method.getResponseBody();
        throw new Exception("HTTP invocation failed: " + method.getStatusLine());
 
            ...
        }
        finally
        {
            method.releaseConnection();
        }
     }
     }
}}}


    byte[] body = method.getResponseBody();


!!!Redirect Handling
    ...
}
finally {


[http://hc.apache.org/httpclient-3.x/redirects.html]
    method.releaseConnection();
}
</pre>


!!!Configuring Retry Count in Presence of Network Errors
=Configuring Retry Count in Presence of Network Errors=


Before starting the client:
Before starting the client:


{{{
<pre>
 
HttpClient httpClient = ...;
      HttpClient httpClient = ...;
int retryCount = 1;
      int retryCount = 1;
httpClient.getParams().setParameter(
      httpClient.getParams().setParameter(
    HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(retryCount , false));
          HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(retryCount , false));
</pre>
 
}}}
 


!!!Setting Socket Connect Timeout
=Setting Socket Connect Timeout=


The socket connect timeout is specified in milliseconds and it is configured using "http.connection.timeout" system property (declared as org.apache.http.params.CoreConnectionPNames.CONNECTION_TIMEOUT):
The socket connect timeout is specified in milliseconds and it is configured using "http.connection.timeout" system property (declared as org.apache.http.params.CoreConnectionPNames.CONNECTION_TIMEOUT):


{{{
<pre>
HttpClient httpClient = ...;
httpClient.getParams().setIntParameter("http.connection.timeout", 5555);
</pre>


      HttpClient httpClient = ...;
=Setting Socket SO_TIMEOUT=
      httpClient.getParams().setIntParameter("http.connection.timeout", 5555);


}}}
The socket SO_TIMEOUT is specified in milliseconds and it is configured using "http.socket.timeout" system property (declared as org.apache.http.params.CoreConnectionPNames.SO_TIMEOUT):
 
Also see [Java Socket].


!!!Setting Socket SO_TIMEOUT
<pre>
HttpClient httpClient = ...;
httpClient.getParams().setIntParameter("http.socket.timeout", 5555);
</pre>


The socket SO_TIMEOUT is specified in milliseconds and it is configured using "http.socket.timeout" system property (declared as org.apache.http.params.CoreConnectionPNames.SO_TIMEOUT):
Also see {{Internal|Socket SO TIMEOUT#Subjects|Socket SO_TIMEOUT}}


{{{
=Configure HttpClient to Accept Self-Signed Certificates=


      HttpClient httpClient = ...;
{{Internal|Configure a Java HTTP Client to Accept Self-Signed Certificates|Configure a Java HTTP Client to Accept Self-Signed Certificates}}
      httpClient.getParams().setIntParameter("http.socket.timeout", 5555);


}}}
=Apache HTTP Components Fluent Adapter=


Also see [Java Socket].
{{External|http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fluent.html}}


!!!Apache HTTP Components Fluent Adapter
=Maven=


[http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fluent.html]
<pre>
<dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.5.1</version>
</dependency>
</pre>


=Multithreaded Execution=
=Multithreaded Execution=
Line 96: Line 93:
=Redirect Handling=
=Redirect Handling=


{{External|http://hc.apache.org/httpcomponents-client-4.5.x/tutorial/html/fundamentals.html#d5e334}}
{{External2|http://hc.apache.org/httpcomponents-client-4.5.x/tutorial/html/fundamentals.html#d5e334|http://hc.apache.org/httpclient-3.x/redirects.html}}


Turn it off:
Turn it off:

Latest revision as of 23:50, 4 April 2019

External

Internal

Overview

Simplest GET usage pattern:

...

HttpMethod method = new GetMethod("http://localhost:8080/");

try {

    int responseCode = httpClient.executeMethod(method);

    if (responseCode != HttpStatus.SC_OK) {

        throw new Exception("HTTP invocation failed: " + method.getStatusLine());
    }

    byte[] body = method.getResponseBody();

    ...
}
finally {

    method.releaseConnection();
}

Configuring Retry Count in Presence of Network Errors

Before starting the client:

HttpClient httpClient = ...;
int retryCount = 1;
httpClient.getParams().setParameter(
    HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(retryCount , false));

Setting Socket Connect Timeout

The socket connect timeout is specified in milliseconds and it is configured using "http.connection.timeout" system property (declared as org.apache.http.params.CoreConnectionPNames.CONNECTION_TIMEOUT):

HttpClient httpClient = ...;
httpClient.getParams().setIntParameter("http.connection.timeout", 5555);

Setting Socket SO_TIMEOUT

The socket SO_TIMEOUT is specified in milliseconds and it is configured using "http.socket.timeout" system property (declared as org.apache.http.params.CoreConnectionPNames.SO_TIMEOUT):

HttpClient httpClient = ...;
httpClient.getParams().setIntParameter("http.socket.timeout", 5555);

Also see

Socket SO_TIMEOUT

Configure HttpClient to Accept Self-Signed Certificates

Configure a Java HTTP Client to Accept Self-Signed Certificates

Apache HTTP Components Fluent Adapter

http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fluent.html

Maven

<dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.5.1</version>
</dependency>

Multithreaded Execution

http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d5e405

In order to allow execution of multiple HTTP requests concurrently on multiple threads, httpclient must be equipped with a pooling connection manager such as PoolingClientConnectionManager.

Redirect Handling

http://hc.apache.org/httpcomponents-client-4.5.x/tutorial/html/fundamentals.html#d5e334
http://hc.apache.org/httpclient-3.x/redirects.html

Turn it off:

RedirectStrategy redirectStrategy = new RedirectStrategy() {
    @Override
    public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException {
        return false;
    }

    @Override
    public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException {
        throw new RuntimeException("getRedirect() NOT YET IMPLEMENTED");
    }
};

... HttpClients.custom().setRedirectStrategy(redirectStrategy).build();

Troubleshooting

httpclient Automatically Follows Redirects

Sometimes this is not the behavior you want, for example when you try to get the OAuth token which is embedded in the redirect Location that you are supposed to parse. See Redirect Handling above.