如何在广播接收器中取消http请求?

时间:2015-07-22 05:40:50

标签: android web-services http broadcastreceiver

在我的应用程序中,我使用广播接收器捕获互联网连接和断开状态。它的工作正常。这是代码:

public class CheckConnectivity extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent arg1) {

        boolean isNotConnected = arg1.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
        if(isNotConnected){
            Toast.makeText(context, "Disconnected", Toast.LENGTH_LONG).show();

        }
        else
        {
            Toast.makeText(context, "Connected", Toast.LENGTH_LONG).show();
        }

    }
}

我在我的应用中使用http网络服务。我在不同的班级写了他们。 HttpConnect.java:

public class HttpConnect {
    public static String finalResponse;
    public static HttpURLConnection con = null;
    public static String  sendGet(String url)  {

        try {
            StringBuffer response = null;
            //String urlEncode = URLEncoder.encode(url, "UTF-8");
            URL obj = new URL(url);
            Log.e("url", obj.toString());

            con = (HttpURLConnection) obj.openConnection();

            // optional default is GET
            con.setRequestMethod("GET");

            //add request header
            con.setConnectTimeout(10000);
            int responseCode = con.getResponseCode();

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream()));
            String inputLine;
            response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            finalResponse  = response.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //print result
        return finalResponse;

    }
}

我的问题是,当广播接收器没有连接时,如何断开或取消http请求。 我在下面尝试过以下代码:

if(isNotConnected){
            Toast.makeText(context, "Disconnected", Toast.LENGTH_LONG).show();
            if(HttpConnect.con != null)
            {
                HttpConnect.con.disconnect();
            }
        }

但它不起作用。当广播接收器捕获丢失的连接时,有人能告诉我如何取消http请求吗?

1 个答案:

答案 0 :(得分:1)

您应该创建一个方法,如下所示:

 public static boolean isOnline(Context mContext) {
        ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
            return true;
        }
        return false;
    }

在您的http通话之前,您应该检查一下,如果它返回true,则表示互联网可用,如果它是false,则表示互联网不可用,您可以停止您的http通话

此外,如果您的通话已经启动,您应该在30秒内设置请求超时值,如果没有互联网,您将获得TimeoutError的例外