0

如何在我的代码中添加请求超时?

下面是我的代码,它为访问服务器调用 http 类并获得响应,但我想添加超时异常

*所以如果服务器在 15 秒内没有响应超时请求,我该怎么办?*

  public class AgAppTransAirTimeTopUp  extends Activity
  {
      private String[][] xmlResponse;

    public void onCreate(Bundle savedInstanceState)
  {

                xmlResponse =  
 AgAppHelperMethods.AgAppXMLParser("AG_IT_App/AgMainServlet?source  
 ="+AgAppHelperMethods.varM      obileNo+"&mobile="+AgAppHelperMethods.varMobileNo+"& 
 pin="+AgAppHelperMethods.getPIN(txtTATpinno.getText().toString())+"&messageType=ATO& 
 channel=INTERNET);
                 if(!AgAppHelperMethods.flag)
                    {

 Toast.makeText(getApplicationContext(), "Invalid Input " , Toast.LENGTH_SHORT).show();
                //       AirTimeProgressDialog.dismiss();
                    }
                    else
                    {

                 Intent j = new Intent(AgAppTransAirTimeTopUp.this,  
        AgAppTransATTPResponse.class);                   
                 MyBean bean = new MyBean();
                 bean.set2DArray(xmlResponse);
                 Bundle b = new Bundle();
                 b.putSerializable("mybean", bean);
                 j.putExtra("obj", b);
                 startActivity(j);
        //            value=false;
                    }        //       
       AirTimeProgressDialog.dismiss();

        }

        }

        catch  (Exception e)
        {
    Toast.makeText(AgAppTransAirTimeTopUp.this, "Invalid Input " ,   
         Toast.LENGTH_SHORT).show();                  
        }



            public class AgAppHelperMethods 
         {

   private static final String LOG_TAG = null;
   private static AgAppHelperMethods instance = null;
   static boolean flag=null != null;




                 public static String smsResponse[][] = new String[20][2];

     String[][] xmlRespone = null;     
   public static AgAppHelperMethods getInstance() 
   {
      if(instance == null) 
          {
             instance = new AgAppHelperMethods();
          }
      return instance;
   }

    public static String getUrl () 
      { 
        String url = "https://xyzaaaaaa/";            
        return url;      
      }

  public static   String[][] AgAppXMLParser( String parUrl) 
  {     
    flag = true;       
    String _node,_element;
    String[][] xmlRespone = null;
    HttpURLConnection urlConnection = null;       
    try 
        {
                String url = AgAppHelperMethods.getUrl() + parUrl;
                URL finalUrl = new URL(url);                
                urlConnection = (HttpURLConnection)  
                       finalUrl.openConnection();
                urlConnection.setConnectTimeout(3000);                
                urlConnection.connect();                
                DocumentBuilderFactory dbf =  
                   DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();
                Document doc = db.parse(finalUrl.toString());

                       doc.getDocumentElement().normalize();              
                NodeList list=doc.getElementsByTagName("*");
                _node=new String();
                _element = new String();
                xmlRespone = new  
                 String[list.getLength()][2];                   
                //this "for" loop is used to parse through the
                //XML document and extract all elements and their
                //value, so they can be displayed on the device 
                for (int i=0;i<list.getLength();i++)
                    {
                        Node value=list.item(i).       
                   getChildNodes().item(0);
                        _node=list.item(i).getNodeName();
                        _element=value.getNodeValue();
                        xmlRespone[i][0] = _node;
                        xmlRespone[i][1] = _element;        
                    }//end for                  
                urlConnection.disconnect();      
        }//end try  
         catch (Exception e)
           {
             flag=false;
             Log.e(LOG_TAG, " Host not responding", e);
             Messages.setMessage("error"+e.getMessage());
         }  
     return xmlRespone;        

  } 
4

1 回答 1

0

捕获超时异常,我认为它可能会对您有所帮助:

HttpGet request = new HttpGet("");

        HttpParams httpParameters = new BasicHttpParams();

        /* Set the timeout in milliseconds until a connection is established.
            The default value is zero, that means the timeout is not used.*/  

        int timeoutConnection = 60*1000*1;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);

        /* Set the default socket timeout (SO_TIMEOUT) 
            in milliseconds which is the timeout for waiting for data.  */
        int timeoutSocket = 60*1000*1;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
        HttpClient client = new DefaultHttpClient(httpParameters);

        try {
            HttpResponse httpResponse = client.execute(request);
        } 
        catch (SocketTimeoutException ex)
        {
            // Do something specific for SocketTimeoutException.
        }
        catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (Exception ex)
        {
            // Do something for all other types of exception.
        }
于 2013-02-27T10:23:12.240 回答