超时后URL连接崩溃应用程序

时间:2014-09-11 17:04:11

标签: java android xml urlconnection connection-timeout

我正在开发一个Android应用程序,其中XML request被发送到服务器,获得的响应在app中用于进一步处理。如果服务器未运行,则问题是app crashes请求timeout之后。我想向Toast展示关于"服务器没有运行的错误"。有人可以帮忙吗?

            try{
            URL url = new URL(server_URL); 

            URLConnection conn=url.openConnection();
            conn.setConnectTimeout(5000);


            conn.setDoOutput(true); 
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); 
            wr.write( 
                    "xxxxxxxxxxxxxxxxxx XML REQUEST xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                    ); 
            wr.flush(); 


             BufferedReader reader;
          reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
          StringBuilder sb = new StringBuilder();
          String line = null;


          while((line = reader.readLine()) != null)
              {
                     // Append server response in string
                     sb.append(line + "\n");
              }


               data = sb.toString();


                  reader.close();

        } catch(IOException ex)
          {

            Toast.makeText(c, "Error: "+ex.getMessage(), Toast.LENGTH_LONG).show();

          }

2 个答案:

答案 0 :(得分:1)

肯定是因为您在主线程上运行网络请求或操作。您使用的是子线程甚至是异步任务吗?

网络操作通常使用异步任务或子线程完成。

尝试这样做:

  AsyncTask<Void, Void, Void> aTask = new AsyncTask<Void,Void,Void>()
    {
      @Override
      protected void onPreExecute()
    {
       //task to run before main network operations start
    }
      @Override
      protected void doInBackground(Void ... s )
     {
        //all the operations to perform should go here
      }

     @Override
     protected void onPostExecute()
     {
       //called when operations have finished and the onBackgroun
     }
    }

此方法用于使用异步任务运行基于网络的操作。 doInBackground方法中不允许Toasts。由于这是一个后台任务,因此不允许干扰主UI上下文,因为它可能导致它挂钩并阻碍ui甚至崩溃。

答案 1 :(得分:0)

将您的捕获更改为:

 catch(Exception ex)
      {
       if (ex instanceof SocketTimeoutException) //time out
            Toast.makeText(c, "Error: "+ex.getMessage(), Toast.LENGTH_LONG).show();

      }