LoginSignup
0
0

More than 3 years have passed since last update.

[ Android ] HTTP通信時に発生するタイムアウトエラー処理

Posted at

AndroidでHttp通信を行う際、起きるタイムアウトの処理について述べる。

サンプル

まずHttp通信は以下のような処理を行う。

        HttpURLConnection connection = null;
        try {
            URL url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(20000);           // 接続タイムアウト
            InputStream is = connection.getInputStream();
        }catch・・・

接続タイムアウト

サンプルではタイムアウトを20secに設定してある。サーバからのレスポンスが20secで返ってこなかった場合、SocketTimeoutExceptionが発生する。この例外のキャッチブロック中にタイムアウトが発生した場合の処理を書けば、例外処理できる。

        }catch(SocketTimeoutException e){
            //タイムアウトが発生したときの処理
        }cacth(IOException e){
            //・・・
        }

IOExceptionはHttpURLConnectionのキャッチブロックによく利用されるので書いている。
これらの順序が逆になるとコンパイルエラーになるので、気を付けて頂きたい。

参考URL

0
0
0

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
0
0