【问题标题】:App crashes when connection is lost while using HttpUrlConnection使用 HttpUrlConnection 时连接丢失时应用程序崩溃
【发布时间】:2021-02-13 01:15:51
【问题描述】:

我正在创建一个从外部 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){}
        
    }
    

那么各位有什么办法可以防止应用崩溃吗?

【问题讨论】:

    标签: java android json crash


    【解决方案1】:

    通过示例设置请求超时:

    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;
    }
    

    【讨论】:

    • 谢谢,我可以通过这种方式检查是否有互联网吗?
    • 在没有连接的情况下,抛出一个你可以控制的异常,根据例子它会等待5秒,可能会更短。
    猜你喜欢
    • 2016-06-29
    • 1970-01-01
    • 1970-01-01
    • 2018-01-28
    • 1970-01-01
    • 2015-10-07
    • 1970-01-01
    • 2014-11-19
    • 2017-11-03
    相关资源
    最近更新 更多