0

我正在使用异步发布方法将一些数据发布到服务器。该帖子工作正常,但如果服务器关闭或无响应,那么我将在应用程序中强制关闭。

我应该如何对发布请求实施超时?

是异步发布到特定 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 
                //===================================================================================================================================

这就是我调用类来执行发布请求的方式

//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 回答