sockettimeoutexception导致应用程序挂起

时间:2014-12-06 06:29:12

标签: java android android-asynctask httpurlconnection

我正在尝试在asynk任务中ping服务器但是当我输入无效的端口号时我得到sockettimeout异常,这会导致应用程序挂起。从未调用asynk任务的post方法&应用程序没有回应我可能知道它为什么会发生。我为此目的使用以下代码。

    private class UrlDataProvider3 extends AsyncTask<String, Void, String>
{

    String ret="";
    int checkStatus;
    Boolean exception=false;
    @Override
    protected String doInBackground(String... url) 
    {

        HttpURLConnection con = null;

        try 
          { 

            Log.i("RAE", "urlData"+url[0]);
            HttpURLConnection.setFollowRedirects(true);
             con = (HttpURLConnection) new URL(url[0]).openConnection();
                 con.setRequestMethod("POST");
              con.setConnectTimeout(20000);

          }


        catch (IOException e)
          {
            if(e.toString().contains("java.net.SocketTimeoutException:"))
            {
                 log.i("Hello","Exception Occurs");
                 return null;
            }

          }
    return ret;
    }
    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        Log.i("RAE"," Asyc finished");

}

1 个答案:

答案 0 :(得分:1)

您需要在SocketTimeoutException块中捕获catch返回语句,然后才会转到onPostExecute

catch (SocketTimeoutException ste)
{
    return null;
}
catch (IOException e)
{
       return null;

}

并在onPostExecute

中处理
@Override
protected void onPostExecute(String result) {

   super.onPostExecute(result);
   Log.i("RAE"," Asyc finished");
   if (result !=null)
   {
       // your code
   }
   else
   {
        // You got an exception
   }