Java URL to InputStream openStream(URL url)

Here you can find the source of openStream(URL url)

Description

convenience method, directly returns a prepared stream

License

Open Source License

Parameter

Parameter Description
url connection target

Return

input stream to that url

Declaration

public static InputStream openStream(URL url) throws IOException 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import java.util.zip.GZIPInputStream;
import java.util.zip.InflaterInputStream;

public class Main {
    public static String userAgent;

    /**//  w ww.  j a  v  a  2 s  .com
     * convenience method, directly returns a prepared stream
     * @param url connection target
     * @return input stream to that url
     */
    public static InputStream openStream(URL url) throws IOException {
        return getInputStream(openConnection(url));
    }

    /**
     * gets the input stream from an url connection
     * @param connection connection which supplies the stream
     * @return connection.getInputStream() which may be wrapped in a decoder
     */
    public static InputStream getInputStream(URLConnection connection) throws IOException {
        InputStream in = connection.getInputStream();
        String encoding = connection.getContentEncoding();
        if (encoding != null) {
            if (encoding.equals("deflate"))
                return new InflaterInputStream(in);
            else if (encoding.equals("gzip"))
                return new GZIPInputStream(in);
            else
                throw new IOException("unexpected encoding: " + encoding);
        }
        return in;
    }

    /**
     * opens a connection to a url and adds the headers (see below) you should use this instead of the method in the URL class
     * @param url the url to connect to
     * @return the set up connection
     */
    public static URLConnection openConnection(URL url) throws IOException {
        URLConnection conn = url.openConnection();
        addHeaders(conn);
        return conn;
    }

    /**
     * adds headers to the url to make it look less like a bot
     * @param conn the connection to modify
     */
    public static void addHeaders(URLConnection conn) throws IOException {
        conn.addRequestProperty("User-Agent", userAgent);
        conn.addRequestProperty("Accept-Language", "en-US,en;q=0.5");
        conn.addRequestProperty("Accept-Encoding", "gzip,deflate");
        conn.addRequestProperty("DNT", "1");
    }
}

Related

  1. openStream(URL url)
  2. openStream(URL url)
  3. openStream(URL url)
  4. openStream(URL url)
  5. openStream(URL url)
  6. openStream(URL url)
  7. openStream(URL url)
  8. openStream(URL url, int connectTimeout, int readTimeout)
  9. openStreamUseCache(URL url)