Here you can find the source of openStream(URL url)
Parameter | Description |
---|---|
url | connection target |
public static InputStream openStream(URL url) throws IOException
//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"); } }