区分URL.openStream中的常见Http错误()

时间:2014-09-19 11:58:23

标签: java android sockets url inputstream

我非常坚持我必须区分Url.openStream()期间发生的常见HTTP错误。主要目的是识别以下HTTP Get请求错误:

  1. 400(错误请求)
  2. 401(未经授权)
  3. 403(禁止)
  4. 404(未找到)
  5. 500(内部服务器错误)
  6. 直到现在我只能通过捕获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;
    }
    

    这可能是一个小问题,但我完全无能为力。请有人帮忙吗

1 个答案:

答案 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块中的紧密连接。