InputStream from a URL

后端 未结 6 390
死守一世寂寞
死守一世寂寞 2020-12-02 14:41

How do I get an InputStream from a URL?

for example, I want to take the file at the url wwww.somewebsite.com/a.txt and read it as an InputStream in Java

6条回答
  •  孤城傲影
    2020-12-02 15:24

    Pure Java:

     urlToInputStream(url,httpHeaders);
    

    With some success I use this method. It handles redirects and one can pass a variable number of HTTP headers asMap. It also allows redirects from HTTP to HTTPS.

    private InputStream urlToInputStream(URL url, Map args) {
        HttpURLConnection con = null;
        InputStream inputStream = null;
        try {
            con = (HttpURLConnection) url.openConnection();
            con.setConnectTimeout(15000);
            con.setReadTimeout(15000);
            if (args != null) {
                for (Entry 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 not 
             * default behavior. See: https://stackoverflow.com/questions/1884230 
             * 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);
        }
    }
    

    Full example call

    private InputStream getInputStreamFromUrl(URL url, String user, String passwd) throws IOException {
            String encoded = Base64.getEncoder().encodeToString((user + ":" + passwd).getBytes(StandardCharsets.UTF_8));
            Map httpHeaders=new Map<>();
            httpHeaders.put("Accept", "application/json");
            httpHeaders.put("User-Agent", "myApplication");
            httpHeaders.put("Authorization", "Basic " + encoded);
            return urlToInputStream(url,httpHeaders);
        }
    

提交回复
热议问题