如何在我的代码中添加请求超时?
下面是我的代码,它为访问服务器调用 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;
}