使用 HttpUrlConnection 时连接丢失时应用程序崩溃
App crashes when connection is lost while using HttpUrlConnection
我正在制作一个 class,它从外部 url 获取 json 数据,如果有连接,它工作正常。如果没有,也会显示错误。
问题是如果 class 正在获取数据时连接丢失,应用程序会崩溃。
这是我的代码:
//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;
}
我正在制作一个 class,它从外部 url 获取 json 数据,如果有连接,它工作正常。如果没有,也会显示错误。 问题是如果 class 正在获取数据时连接丢失,应用程序会崩溃。
这是我的代码:
//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;
}