HttpClientフル装備版
package hello.org.apache.commons.httpclient;
import java.io.IOException;
import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
/**
* フル装備版
*/
public class HelloHttpClientFullMain {
public static void main(String[] args) {
String url = "http://localhost:8080/myweb/hello.html";
HttpClient client = null;
HttpMethod method = null;
{
// マルチスレッド対応
client = new HttpClient(new MultiThreadedHttpConnectionManager());
// ソケットタイムアウトを 1秒にする。→タイムアウトは connection manager で設定
client.getParams().setParameter("http.socket.timeout",
new Integer(1000));
{
// 基本認証
// HTTPClient 初期化
Credentials credentials = new UsernamePasswordCredentials(
"userid", "password");
AuthScope authscope = new AuthScope("localhost", 8080);
client.getState().setCredentials(authscope, credentials);
client.getParams().setAuthenticationPreemptive(true);
}
}
{
method = new GetMethod(url);
method.addRequestHeader("Connection", "close");
// リトライは3回。リトライ間隔500ms
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false) {
@Override
public boolean retryMethod(HttpMethod method,
IOException exception, int executionCount) {
boolean retry = super.retryMethod(method,
exception, executionCount);
if (retry) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
return retry;
}
});
}
try {
client.executeMethod(method);
byte[] responseBody = method.getResponseBody();
System.out.println(new String(responseBody));
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
method.releaseConnection();
client.getHttpConnectionManager().closeIdleConnections(0);
}
}
}