TimeoutRetry

HelloHttpClientTimeoutRetryMain

■コード

package hello.org.apache.commons.httpclient;

import java.io.IOException;

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.methods.GetMethod;

import org.apache.commons.httpclient.params.HttpMethodParams;

public class HelloHttpClientTimeoutRetryMain {

public static void main(String[] args) {

String url = "http://localhost:8080/myweb/hello.html";

HttpClient client = new HttpClient(

new MultiThreadedHttpConnectionManager());

// ソケットタイムアウトを 1秒にする。

client.getParams().setParameter("http.socket.timeout",

new Integer(1000));

HttpMethod method = new GetMethod(url);

// リトライは3回。デフォルトではリトライ間隔は無し。

method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,

new DefaultHttpMethodRetryHandler(3, false));

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);

}

}

}

■実行結果

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Hello</title>

</head>

<body>

Hello.

</body>

</html>