Httpclient for Android

直前のエントリで言及したように、JSDKレベルのHTTP接続はどうやら使い物にならないぽいので、Android SDKに同梱されているApache HttpClientを使うことにした。

Android内部で使用されているHttpClientのバージョンはそのソースコードから、4.0相当と思われる。

 * $HeadURL: http://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk/module-client/src/main/java/org/apache/http/client/HttpClient.java $
 * $Revision: 676020 $
 * $Date: 2008-07-11 09:38:49 -0700 (Fri, 11 Jul 2008) $

/**
 * Interface for an HTTP client.
 * HTTP clients encapsulate a smorgasbord of objects required to
 * execute HTTP requests while handling cookies, authentication,
 * connection management, and other features.
 * Thread safety of HTTP clients depends on the implementation
 * and configuration of the specific client.
 *
 * @author Roland Weber
 *
 *
 *  * @version   $Revision: 676020 $
 *
 * @since 4.0
 */

ということでHttpClient4のドキュメントをざっと眺めていたのだが、

5.3. Automcatic redirect handling

HttpClient handles all types of redirects automatically, except those explicitly prohibited by the HTTP specification as requiring user intervention. See Other (status code 303) redirects on POST and PUT requests are converted to GET requests as required by the HTTP specification.

5.3. Automcatic redirect handling
- HttpClient Tutorial - 5. HTTP client service - 5.3. Automcatic redirect handling

リダイレクトは自動的に処理してくれるらしい。なんてこったい。

ぱっと見、HttpClient 4.xは各種フィルタ-ハンドラをチェインすることで機能の挿入、変更を容易くしているようだが、リダイレクトに関しても以下のように、デフォルトの実装ではリダイレクト用のハンドラが用意されており、確かに処理に組込まれているようだ。

    • DefaultHttpClient.java
    @Override
    protected RedirectHandler createRedirectHandler() {
        return new DefaultRedirectHandler();
    }
    • DefaultRedirectHandler.java
:
public boolean isRedirectRequested(
        final HttpResponse response,
        final HttpContext context) {
    if (response == null) {
        throw new IllegalArgumentException("HTTP response may not be null");
    }
    int statusCode = response.getStatusLine().getStatusCode();
    switch (statusCode) {
    case HttpStatus.SC_MOVED_TEMPORARILY:
    case HttpStatus.SC_MOVED_PERMANENTLY:
    case HttpStatus.SC_SEE_OTHER:
    case HttpStatus.SC_TEMPORARY_REDIRECT:
        return true;
    default:
        return false;
    } //end of switch
}
:

ということでHTTP通信に関しては、JSDKベースからHttpClientベースに全て組み直すことにする。