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

Java 异步post方法中设置连接超时的方法,java,android,http-post,connection-timeout,Java,Android,Http Post,Connection Timeout,我正在使用异步post方法将一些数据发布到服务器。post工作正常,但是如果服务器关闭或没有响应,那么我将在应用程序中强制关闭 如何实现post请求的超时? 这是异步发布到特定url的类: //=================================================================================================================================== //sending EmailAd

我正在使用异步post方法将一些数据发布到服务器。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 
                //===================================================================================================================================
如果服务器没有响应或不可用,在特定时间后,我应该如何实现连接超时?

编辑:

如何使用警报通知用户连接已超时?我应该将警报放在何处以及在何种情况下?


提前谢谢

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

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

HttpConnectionParams.setSoTimeout(httpParams, 10000);

HttpClient client = new DefaultHttpClient(httpParams);  

@kittu88您如何处理响应?我的意思是你有没有为此创建处理程序?是的,你可以检查上面的类。如果你觉得有什么需要修改的话,你可以建议我that@kittu88您可以捕获异常捕获(SocketTimeoutException ex){//为SocketTimeoutException执行特定操作。}如果您不介意,可以建议在我的代码中进行编辑吗?@kittu88请立即检查。。。不过我还没有编译
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);

HttpConnectionParams.setSoTimeout(httpParams, 10000);

HttpClient client = new DefaultHttpClient(httpParams);