java - 假设连接丢失,如何停止 HTTP 连接?

标签 java android

以下代码来自 Facebook Android SDK,用于与 Facebook 的所有交互。我正在使用它在持有唤醒锁的服务中搜索和/或发布到 Facebook。因此,如果手机以某种方式失去了互联网连接,我希望该服务放弃并终止,以避免浪费电池。

我不明白的是你将如何中断这样的事情,因为问题可能会在此方法中的任何时候发生。我也不知道 HTTPUrlConnection 中是否已经存在用于连接超时的内置机制。

public static String openUrl(String url, String method, Bundle params)
        throws MalformedURLException, IOException {
    // random string as boundary for multi-part http post
    String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
    String endLine = "\r\n";

    OutputStream os;

    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }
    Log.d("Facebook-Util", method + " URL: " + url);
    HttpURLConnection conn = (HttpURLConnection) new URL(url)
            .openConnection();
    conn.setRequestProperty("User-Agent", System.getProperties()
            .getProperty("http.agent") + " FacebookAndroidSDK");
    if (!method.equals("GET")) {
        Bundle dataparams = new Bundle();
        for (String key : params.keySet()) {
            if (params.getByteArray(key) != null) {
                dataparams.putByteArray(key, params.getByteArray(key));
            }
        }

        // use method override
        if (!params.containsKey("method")) {
            params.putString("method", method);
        }

        if (params.containsKey("access_token")) {
            String decoded_token = URLDecoder.decode(params
                    .getString("access_token"));
            params.putString("access_token", decoded_token);
        }

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type",
                "multipart/form-data;boundary=" + strBoundary);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.connect();
        os = new BufferedOutputStream(conn.getOutputStream());

        os.write(("--" + strBoundary + endLine).getBytes());
        os.write((encodePostBody(params, strBoundary)).getBytes());
        os.write((endLine + "--" + strBoundary + endLine).getBytes());

        if (!dataparams.isEmpty()) {

            for (String key : dataparams.keySet()) {
                os.write(("Content-Disposition: form-data; filename=\""
                        + key + "\"" + endLine).getBytes());
                os.write(("Content-Type: content/unknown" + endLine + endLine)
                        .getBytes());
                os.write(dataparams.getByteArray(key));
                os.write((endLine + "--" + strBoundary + endLine)
                        .getBytes());

            }
        }
        os.flush();
    }

    String response = "";
    try {
        response = read(conn.getInputStream());
    } catch (FileNotFoundException e) {
        // Error Stream contains JSON that we can parse to a FB error
        response = read(conn.getErrorStream());
    }
    return response;
}

最佳答案

文档说:

httpConn.setConnectTimeout(HTTP_CONNECT_TIMEOUT);
httpConn.setReadTimeout(HTTP_READ_TIMEOUT);

参见http://developer.android.com/reference/java/net/URLConnection.html#setConnectTimeout(int )

关于java - 假设连接丢失,如何停止 HTTP 连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5545081/

相关文章:

Java 7 在一些基本的解析任务上比 Java 6 慢 8 倍

java - 如何使用java创建简单的NFC程序?

java - 作业调度程序的作业调度不一致

java - 修改一个Bitmap后,如何修改 "modified"Bitmap等?

Java:在输出流中多次写入带有新参数的同一对象

java - android webView 中的 ScrollView 不显示键盘

android - ScrollView 中的线性布局不占据全高

java - 媒体 Controller 不工作

java - 未处理的异常如何影响 JVM?

android - 将顶部 imageView 与 relativeLayout 的中心对齐