How to stop an HTTP connection, assuming lost connection?
The following code is from the Facebook Android SDK, and is used for all the interactions with Facebook. I'm using it to search and/or post to Facebook in a service that's holding a wakelock. So if the phone somehow loses Internet connectivity, I want the service to give up and terminate to avoid wasting battery.
What I don't understand is how you would go about interrupting something like this, because the problem might happen at any point within this method. I also don't know if there is somehow already a built-in mechanism for connection timeouts in HTTPUrlConnection.
public static String openUrl(String url, String method, Bundle params)
throws MalformedURLException, IOEx开发者_JAVA技巧ception {
// 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;
}
Documentation says:
httpConn.setConnectTimeout(HTTP_CONNECT_TIMEOUT);
httpConn.setReadTimeout(HTTP_READ_TIMEOUT);
see http://developer.android.com/reference/java/net/URLConnection.html#setConnectTimeout(int)
精彩评论