我非常坚持我必须区分Url.openStream()期间发生的常见HTTP错误。主要目的是识别以下HTTP Get请求错误:
直到现在我只能通过捕获FileNotFoundException来识别404。这是我的代码段:
try {
file.createNewFile();
URL url = new URL(fileUrl);
URLConnection connection = url.openConnection();
connection.connect();
// download the file
InputStream input = new BufferedInputStream(url.openStream());
// store the file
OutputStream output = new FileOutputStream(file);
byte data[] = new byte[1024];
int count;
while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
Log.e(TAG, "Writing");
}
output.flush();
output.close();
input.close();
result = HTTP_SUCCESS;
} catch (FileNotFoundException fnfe) {
Log.e(TAG, "Exception found FileNotFoundException=" + fnfe);
Log.e(TAG, "FILE NOT FOUND");
result = HTTP_FILE_NOT_FOUND;
} catch (Exception e) {
Log.e(TAG, "Exception found=" + e);
Log.e(TAG, e.getMessage());
Log.e(TAG, "NETWORK_FAILURE");
result = NETWORK_FAILURE;
}
这可能是一个小问题,但我完全无能为力。请有人帮忙吗
答案 0 :(得分:2)
如果您使用HTTP将您的连接转换为HttpUrlConnection
,则在使用connection.getResponseCode()
打开流检查响应状态代码之前:
connection = (HttpURLConnection) new URL(url).openConnection();
/* ... */
final int responseCode = connection.getResponseCode();
switch (responseCode) {
case 404:
/* ... */
case 200: {
InputStream input = new BufferedInputStream(url.openStream());
/* ... */
}
}
不要忘记finally
块中的紧密连接。