Java URLConnection Create openConnection(URL url)

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

Description

opens a connection to a url and adds the headers (see below) you should use this instead of the method in the URL class

License

Open Source License

Parameter

Parameter Description
url the url to connect to

Return

the set up connection

Declaration

public static URLConnection openConnection(URL url) throws IOException 

Method Source Code

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

import java.io.IOException;

import java.net.URL;
import java.net.URLConnection;

public class Main {
    public static String userAgent;

    /**//from w  w  w. ja v  a 2 s  .  co m
     * 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. openConnection(String urlPath)
  2. openConnection(URL localURL)
  3. openConnection(URL url)
  4. openConnection(URL url)
  5. openConnection(URL url)
  6. openConnectionForceNoProxy(URL url)
  7. openConnectionTo(URL descriptor)
  8. openInputStream(URL url)
  9. openURL(String url)