2

私のアクティビティは AsynTask を使用して http リクエストを実行します。Web サーバーが応答しない場合に HttpResponse を処理する方法は? 現在、Web サーバーがダウンしているとき、AsynTask は「HttpResponse response = client.execute(httppost);」で停止しました。そして何もしません。この応答を処理して何かをする必要がありますが、「実行」以下のコードは実行されません。

バックグラウンドタスクは次のとおりです。

    protected String doInBackground(String... params) {
        HttpClient client = new DefaultHttpClient();
        String result = null;
        try {
            // Add your data
            List<NameValuePair> postData = new ArrayList<NameValuePair>(2);
            postData.add(new BasicNameValuePair("session_id", session_id));
            postData.add(new BasicNameValuePair("i_key", params[0]));

            HttpPost httppost = new HttpPost( "http://my.webserver.com/getInfo.php");
            httppost.setEntity(new UrlEncodedFormEntity(postData));

            HttpResponse response = client.execute(httppost);
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(responseEntity.getContent(),
                                "UTF-8"));
                result = reader.readLine().toString();
            } else {
              Toast.makeText(this, "DDDDDDD",Toast.LENGTH_LONG).show();
            }

        } catch (IllegalArgumentException e1) {
            e1.printStackTrace();
        } catch (IOException e2) {
            e2.printStackTrace();
        }
        return result;
    }

Web サーバーがダウンして応答しない場合、応答を処理するにはどうすればよいですか?

4

1 に答える 1

3

クライアントの接続のタイムアウトを設定する必要があります。例えば:

protected String doInBackground(String... params) {
    HttpParams httpParameters = new BasicHttpParams();
    // set the connection timeout and socket timeout parameters (milliseconds)
    HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
    HttpConnectionParams.setSoTimeout(httpParameters, 5000);

    HttpClient client = new DefaultHttpClient(httpParameters);
    . . . // the rest of your code
}
于 2013-04-21T17:05:15.817 に答える