LoginSignup
52
51

More than 5 years have passed since last update.

HttpUrlConnection とエラーハンドリング

Last updated at Posted at 2014-04-23

HttpUrlConnection の概要

ストリームを用いた汎用の Network I/O のためのインタフェースとして、URLConnectionがあり、このうち HTTP に基づいたものがHttpUrlConnectionです。さらにこの子クラスとして、HttpsUrlConnectionもあります。

Input

URLConnection#getInputStream()で得られるInputStreamを読み取ることで、レスポンスのデータを取得します。

Output

URLConnection#getOutputStream()で得られるOutputStreamにデータを書き出すことで、リクエストを作成します。
OutputStreamclose()するまでリクエストは送られません。

Error

サーバから、4xxや5xxなどのエラーレスポンスが返されると、FileNotFoundExceptionがスローされます(コードはここのL176)。

ただし、URLConnectionのインタフェースのほとんどはIOExceptionをスローすることがドキュメントに明示されているのみで、IDE のコード補完にまかせてコードを書くと、IOExceptionをキャッチするブロックに全てが吸収されてしまいます。

FileNotFoundExceptionをキャッチした場合で、サーバがエラーレスポンスに何らかのデータをくっつけて来た場合、HttpUrlConnection#getErrorStream()InputStreamを取得し、エラーレスポンスを読み取ります。

よって、愚直に書くと以下の様な悲しいコードになります。


InputStream in = null;
try {
    in = connection.getInputStream();
    // ...
} catch (FileNotFoundException e) { // IOException をキャッチするより先に FileNotFoundException をキャッチしないと IOException のキャッチブロックに行くのでこうする
    System.err.println(e);
    InputStream err = null;
    try {
        err = connection.getErrorStream();
        // 4xx または 5xx なレスポンスのボディーを読み取る
        // ...
    } catch (IOException e) {
        System.err.println(e);
    } finally {
        if (err != null) {
            try {
                err.close();
            } catch (IOException e) {
                System.err.println(e);
            }
        }
    }
} catch (IOException e) {
    System.err.println(e);
} finally {
    if (in != null) {
        try {
            in.close();
        } catch (IOException e) {
            System.err.println(e);
        }
    }
    if (connection != null) {
        connection.disconnect();
    }
}
52
51
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
52
51