当使用HttpUrlConnection时连接丢失时应用程序崩溃



我正在制作一个从外部url获取json数据的类,如果有连接,它可以正常工作。如果没有,也会显示错误。问题是,如果在类获取数据时连接丢失,则应用程序会崩溃。

下面是我的代码:
//I always check connection before calling the class
class GetPost extends AsyncTask<String, String, String>
{

Context c;
String res;
public GetPost(Context c){
this.c=c;
}
@Override
protected void onPreExecute()
{

super.onPreExecute();
Earn.statu.setText("Loading post...");
}



@Override
protected String doInBackground(String[] p1)
{
try{
URL u = new URL(p1[0]);
HttpURLConnection con = (HttpURLConnection) u.openConnection();
InputStream is = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
res = br.readLine();
}   
catch (MalformedURLException e){}
catch (IOException e){}


return res;
}
@Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);    
try{
JSONObject   jo = new JSONObject(res);
Earn.getVideoData(c,
jo.getString("pid"),
jo.getInt("duration"),
jo.getInt("id")
);
}catch(JSONException a){}

}

所以伙计们有什么解决方案来防止应用程序崩溃吗?

设置请求超时时间,示例:

try {
HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
con.setRequestMethod("HEAD");
con.setConnectTimeout(5000); //set timeout to 5 seconds
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
} catch (java.net.SocketTimeoutException e) {
return false;
} catch (java.io.IOException e) {
return false;
}

最新更新