首页 文章

在异步post方法中设置连接超时的方法

提问于
浏览
0

我正在使用 asynchronous post method 将一些数据发布到服务器 . 该帖子工作正常,但如果服务器关闭或无响应,那么我将在应用程序中关闭一个强制关闭 .

How should I implement a timeout to the post request?

这是 class which is asynchronously posting to a particular 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 
                //===================================================================================================================================

我就是这样 calling the class to execute the post request

//sending request for login

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

What should I do to implement a connection timeout after a particular time if the server does not respond or is not available?

Edited:

How do I notify the user using an alert that the connection has timed out? Where should I put the alert and during which condition?

提前致谢!

1 回答

  • 2

    你可以试试这个,我设定了10秒 . 这里...

    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
    
    HttpConnectionParams.setSoTimeout(httpParams, 10000);
    
    HttpClient client = new DefaultHttpClient(httpParams);
    

相关问题