通过 URL 查询字符串从文件读取 InputStream

Read InputStream from file via URL query string

当 URL 是查询字符串而不是直接 [=21] 时,是否可以使用 java URL.openStream() 方法将文件读入输入流=] 到一个文件?例如。我的代码是:

URL myURL = new URL("http://www.test.com/myFile.doc");
InputStream is = myURL.openStream(); 

这适用于直接文件 link。但是如果 URL 是 http://www.test.com?file=myFile.doc 呢?我还能从服务器响应中获取文件流吗?

谢谢!

URL class 适用于任何 url,包括:

  • new URL("http://www.example.com/");
  • new URL("file://C/windows/system32/cmd.exe");
  • new URL("ftp://user:password@example.com/filename;type=i");

由应用程序来处理数据,例如下载数据,或将其视为纯文本。

通常是的,它会起作用。

但请注意,URL.openStream() 方法不遵循重定向,并且在指定一些额外的 HTTP 行为时不够灵活:请求类型、headers 等

我建议改用 Apache HTTP Client

final CloseableHttpClient httpclient = HttpClients.createDefault();         
final HttpGet request = new HttpGet("http://any-url");

try (CloseableHttpResponse response = httpclient.execute(request)) {
    final int status = response.getStatusLine().getStatusCode();

    if (status == 200) {
        final InputStream is = response.getEntity().getContent();
    } else {
        throw new IOException("Got " + status + " from server!");
    }
}
finally {
    request.reset();
}