Java 区分URL.openStream()中常见的Http错误
由于我必须区分Url.openStream()过程中出现的常见HTTP错误,因此我被卡住了。。主要目的是识别以下HTTP Get请求错误:Java 区分URL.openStream()中常见的Http错误,java,android,sockets,url,inputstream,Java,Android,Sockets,Url,Inputstream,由于我必须区分Url.openStream()过程中出现的常见HTTP错误,因此我被卡住了。。主要目的是识别以下HTTP Get请求错误: 400(错误请求) 401(未经授权) 403(禁止) 404(未找到) 500(内部服务器错误) 到目前为止,通过捕获FileNotFoundException,我只能识别404。这是我的代码片段: try { file.createNewFile(); URL url = new URL(fileUrl); URLConnecti
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;
}
这可能是个小问题,但我完全不知道。如果您使用HTTP将连接强制转换到
HttpUrlConnection
,在打开流之前,请使用connection.getResponseCode()检查响应状态代码。
:
不要忘记在最后
块中关闭连接。如果您使用HTTP——HTTP和HTTPS?或者仅仅是对FTP或者其他东西?
connection = (HttpURLConnection) new URL(url).openConnection();
/* ... */
final int responseCode = connection.getResponseCode();
switch (responseCode) {
case 404:
/* ... */
case 200: {
InputStream input = new BufferedInputStream(url.openStream());
/* ... */
}
}