0

非同期のpostメソッドを使用して、サーバーにデータを投稿しています。投稿は正常に機能していますが、サーバーがダウンしているか応答しない場合は、アプリケーションを強制的に閉じています。

POSTリクエストにタイムアウトを実装するにはどうすればよいですか?

これは、特定のURLに非同期で投稿するクラスです

    //===================================================================================================================================
//sending EmailAddress and Password to server
//===================================================================================================================================
private class MyAsyncTask extends AsyncTask<String, Integer, Double>{


    @Override
    protected Double doInBackground(String... params) {
        // TODO Auto-generated method stub
        postData(params[0],params[1]);
        return null;
    }

    protected void onPostExecute(Double result){


        if(responseBody.contains("TRUE"))
        {
            String raw=responseBody;
            raw = raw.substring(0, raw.lastIndexOf("<"));
            raw = raw.substring(raw.lastIndexOf(">") + 1, raw.length());
            String [] contents = raw.split(",");
            //extracting user name and user id from response
            String user_name=contents[1];
            String student_code=contents[2];
            //save user name and user id in preference
            saveInPreference("user_name",user_name);
            saveInPreference("student_code",student_code);

            //login is successful, going to next activity       
            Intent intent = new Intent(LoginActivity.this, TakeTestActivity.class);
            //hiding progress bar
            progress.dismiss();
            finish();
            LoginActivity.this.startActivity(intent);

        }

        else
        {
            //hiding progress bar
            progress.dismiss();
            create_alert("Attention!", "Please provide valid userid and password");
        }
    }

    protected void onProgressUpdate(Integer... progress){

    }

    public void postData(String emailId,String passwrd) {

**//EDIT START**
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);

HttpConnectionParams.setSoTimeout(httpParams, 10000);

HttpClient httpclient = new DefaultHttpClient(httpParams); 
**//EDIT END** 

        // Create a new HttpClient and Post Header
        //HttpClient httpclient = new DefaultHttpClient();

        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(LoginActivity.this);
        final String url_first = preferences.getString("URLFirstPart","");
        HttpPost httppost = new HttpPost(url_first+"ValidateLogin");

        try {
            // Data that I am sending
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("EmailId", emailId));
            nameValuePairs.add(new BasicNameValuePair("Password", passwrd));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                    **//EDIT START**
                    try 
                    {
            // Execute HTTP Post Request
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            responseBody = EntityUtils.toString(response.getEntity());
                   } 
                   catch (SocketTimeoutException ex)
                   {
                        // Do something specific for SocketTimeoutException.
                   }
                   **//EDIT END**

            //Log.d("result", responseBody);
        } 
        catch (Throwable t ) {

        } 
    }
}
                //===================================================================================================================================
                //END sending EmailAddress and Password to server 
                //===================================================================================================================================

これは私がpostリクエストを実行するためにクラスを呼び出す方法です:

//sending request for login

new MyAsyncTask().execute(txtUsername.getText().toString(),txtPassword.getText().toString());

サーバーが応答しない、または使用できない場合、特定の時間の後に接続タイムアウトを実装するにはどうすればよいですか?

編集:

接続がタイムアウトしたことをアラートを使用してユーザーに通知するにはどうすればよいですか?アラートをどこに、どの状態で配置する必要がありますか?

前もって感謝します!

4

1 に答える 1

2

あなたはこれを試すことができます、私は10秒を設定しました。ここ...

HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);

HttpConnectionParams.setSoTimeout(httpParams, 10000);

HttpClient client = new DefaultHttpClient(httpParams);  
于 2013-03-20T10:51:17.040 に答える