Whi*_*ear 108 java url inputstream
如何从URL获取InputStream?
例如,我想将文件放在url上,wwww.somewebsite.com/a.txt
并通过servlet将其作为Java中的InputStream读取.
我试过了
InputStream is = new FileInputStream("wwww.somewebsite.com/a.txt");
Run Code Online (Sandbox Code Playgroud)
但我得到的是一个错误:
java.io.FileNotFoundException
Run Code Online (Sandbox Code Playgroud)
Bal*_*usC 207
使用java.net.URL#openStream()
正确的URL(包括协议!).例如
InputStream input = new URL("http://www.somewebsite.com/a.txt").openStream();
// ...
Run Code Online (Sandbox Code Playgroud)
whi*_*rra 17
尝试:
final InputStream is = new URL("http://wwww.somewebsite.com/a.txt").openStream();
Run Code Online (Sandbox Code Playgroud)
use*_*421 10
(a)wwww.somewebsite.com/a.txt
不是'文件网址'.它根本不是URL.如果你把http://
它放在它的前面它将是一个HTTP URL,这显然是你想要的.
(b)FileInputStream
用于文件,而不是URL.
(c)从任何 URL 获取输入流的方式是通过URL.openStream(),
或URL.getConnection().getInputStream(),
相当于你,但你可能有其他理由先得到URLConnection
并使用它.
纯Java:
urlToInputStream(url,httpHeaders);
Run Code Online (Sandbox Code Playgroud)
我使用这种方法取得了一些成功。它处理重定向,并且可以将可变数量的HTTP 标头作为Map<String,String>
. 它还允许从 HTTP 重定向到 HTTPS。
private InputStream urlToInputStream(URL url, Map<String, String> args) {
HttpURLConnection con = null;
InputStream inputStream = null;
try {
con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(15000);
con.setReadTimeout(15000);
if (args != null) {
for (Entry<String, String> e : args.entrySet()) {
con.setRequestProperty(e.getKey(), e.getValue());
}
}
con.connect();
int responseCode = con.getResponseCode();
/* By default the connection will follow redirects. The following
* block is only entered if the implementation of HttpURLConnection
* does not perform the redirect. The exact behavior depends to
* the actual implementation (e.g. sun.net).
* !!! Attention: This block allows the connection to
* switch protocols (e.g. HTTP to HTTPS), which is <b>not</b>
* default behavior. See: /sf/ask/131896131/
* for more info!!!
*/
if (responseCode < 400 && responseCode > 299) {
String redirectUrl = con.getHeaderField("Location");
try {
URL newUrl = new URL(redirectUrl);
return urlToInputStream(newUrl, args);
} catch (MalformedURLException e) {
URL newUrl = new URL(url.getProtocol() + "://" + url.getHost() + redirectUrl);
return urlToInputStream(newUrl, args);
}
}
/*!!!!!*/
inputStream = con.getInputStream();
return inputStream;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
Run Code Online (Sandbox Code Playgroud)
完整的调用示例
private InputStream getInputStreamFromUrl(URL url, String user, String passwd) throws IOException {
String encoded = Base64.getEncoder().encodeToString((user + ":" + passwd).getBytes(StandardCharsets.UTF_8));
Map<String,String> httpHeaders=new Map<>();
httpHeaders.put("Accept", "application/json");
httpHeaders.put("User-Agent", "myApplication");
httpHeaders.put("Authorization", "Basic " + encoded);
return urlToInputStream(url,httpHeaders);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
144188 次 |
最近记录: |