gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 15:53:26 24 4
gpt4 key购买 nike

以下代码来自 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com