Example usage for java.net HttpURLConnection connect

List of usage examples for java.net HttpURLConnection connect

Introduction

In this page you can find the example usage for java.net HttpURLConnection connect.

Prototype

public abstract void connect() throws IOException;

Source Link

Document

Opens a communications link to the resource referenced by this URL, if such a connection has not already been established.

Usage

From source file:Main.java

/**
 * Given a string url, connects and returns response code
 *
 * @param urlString       string to fetch
 * @param readTimeOutMs       read time out
 * @param connectionTimeOutMs       connection time out
 * @param urlRedirect       should use urlRedirect
 * @param useCaches       should use cache
 * @return httpResponseCode http response code
 * @throws IOException//from  w ww .ja v a  2 s .c  o  m
 */

public static int checkUrlWithOptions(String urlString, int readTimeOutMs, int connectionTimeOutMs,
        boolean urlRedirect, boolean useCaches) throws IOException {
    URL url = new URL(urlString);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setReadTimeout(readTimeOutMs /* milliseconds */);
    connection.setConnectTimeout(connectionTimeOutMs /* milliseconds */);
    connection.setRequestMethod("GET");
    connection.setInstanceFollowRedirects(urlRedirect);
    connection.setUseCaches(useCaches);
    // Starts the query
    connection.connect();
    int responseCode = connection.getResponseCode();
    connection.disconnect();
    return responseCode;
}

From source file:com.mk4droid.IMC_Services.Download_Data.java

/**
 * Download Image from a certain url//  w w  w . ja v  a 2 s  .com
 * 
 * @param fullPath the url of the image
 * @return
 */
public static byte[] Down_Image(String fullPath) {

    try {
        //----- Split----
        String[] AllInfo = fullPath.split("/");

        // Encode filename as UTF8 -------
        String fnExt = AllInfo[AllInfo.length - 1];

        String fnExt_UTF8 = URLEncoder.encode(fnExt, "UTF-8");

        //- Replace new fn to old
        AllInfo[AllInfo.length - 1] = fnExt_UTF8;

        //------ Concatenate to a single string -----
        String newfullPath = AllInfo[0];
        for (int i = 1; i < AllInfo.length; i++)
            newfullPath += "/" + AllInfo[i];

        // empty space becomes + after UTF8, then replace with %20
        newfullPath = newfullPath.replace("+", "%20");

        //------------ Download -------------
        URL myFileUrl = new URL(newfullPath);

        HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
        conn.setDoInput(true);
        conn.setConnectTimeout(10000);
        conn.connect();
        InputStream isBitmap = conn.getInputStream();
        return readBytes(isBitmap);

    } catch (Exception e) {
        Log.e(Constants_API.TAG, "Download_Data: Down_Image: Error in http connection " + e.getMessage());
        return null;
    }

}

From source file:Main.java

public static String getHtml(String getUrl, String charsetName) {
    String html = "";
    URL url;/* w ww  . j a v a 2  s.co  m*/
    try {
        url = new URL(getUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("User-Agent", userAgent);
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Cache-Control", "no-cache");
        connection.setReadTimeout(timeout);
        connection.setFollowRedirects(true);
        connection.connect();
        InputStream inStrm = connection.getInputStream();

        BufferedReader br = new BufferedReader(new InputStreamReader(inStrm, charsetName));
        String temp = "";

        while ((temp = br.readLine()) != null) {
            html = html + (temp + '\n');
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return html;
}

From source file:hudson.Main.java

/**
 * Run command and send result to {@code ExternalJob} in the {@code external-monitor-job} plugin.
 * Obsoleted by {@code SetExternalBuildResultCommand} but kept here for compatibility.
 *//*w w  w.j a  v  a 2 s  .  co m*/
public static int remotePost(String[] args) throws Exception {
    String projectName = args[0];

    String home = getHudsonHome();
    if (!home.endsWith("/"))
        home = home + '/'; // make sure it ends with '/'

    // check for authentication info
    String auth = new URL(home).getUserInfo();
    if (auth != null)
        auth = "Basic " + new Base64Encoder().encode(auth.getBytes("UTF-8"));

    {// check if the home is set correctly
        HttpURLConnection con = open(new URL(home));
        if (auth != null)
            con.setRequestProperty("Authorization", auth);
        con.connect();
        if (con.getResponseCode() != 200 || con.getHeaderField("X-Hudson") == null) {
            System.err.println(home + " is not Hudson (" + con.getResponseMessage() + ")");
            return -1;
        }
    }

    URL jobURL = new URL(home + "job/" + Util.encode(projectName).replace("/", "/job/") + "/");

    {// check if the job name is correct
        HttpURLConnection con = open(new URL(jobURL, "acceptBuildResult"));
        if (auth != null)
            con.setRequestProperty("Authorization", auth);
        con.connect();
        if (con.getResponseCode() != 200) {
            System.err.println(jobURL + " is not a valid external job (" + con.getResponseCode() + " "
                    + con.getResponseMessage() + ")");
            return -1;
        }
    }

    // get a crumb to pass the csrf check
    String crumbField = null, crumbValue = null;
    try {
        HttpURLConnection con = open(
                new URL(home + "crumbIssuer/api/xml?xpath=concat(//crumbRequestField,\":\",//crumb)'"));
        if (auth != null)
            con.setRequestProperty("Authorization", auth);
        String line = IOUtils.readFirstLine(con.getInputStream(), "UTF-8");
        String[] components = line.split(":");
        if (components.length == 2) {
            crumbField = components[0];
            crumbValue = components[1];
        }
    } catch (IOException e) {
        // presumably this Hudson doesn't use CSRF protection
    }

    // write the output to a temporary file first.
    File tmpFile = File.createTempFile("jenkins", "log");
    try {
        int ret;
        try (OutputStream os = Files.newOutputStream(tmpFile.toPath());
                Writer w = new OutputStreamWriter(os, "UTF-8")) {
            w.write("<?xml version='1.1' encoding='UTF-8'?>");
            w.write("<run><log encoding='hexBinary' content-encoding='" + Charset.defaultCharset().name()
                    + "'>");
            w.flush();

            // run the command
            long start = System.currentTimeMillis();

            List<String> cmd = new ArrayList<String>();
            for (int i = 1; i < args.length; i++)
                cmd.add(args[i]);
            Proc proc = new Proc.LocalProc(cmd.toArray(new String[0]), (String[]) null, System.in,
                    new DualOutputStream(System.out, new EncodingStream(os)));

            ret = proc.join();

            w.write("</log><result>" + ret + "</result><duration>" + (System.currentTimeMillis() - start)
                    + "</duration></run>");
        } catch (InvalidPathException e) {
            throw new IOException(e);
        }

        URL location = new URL(jobURL, "postBuildResult");
        while (true) {
            try {
                // start a remote connection
                HttpURLConnection con = open(location);
                if (auth != null)
                    con.setRequestProperty("Authorization", auth);
                if (crumbField != null && crumbValue != null) {
                    con.setRequestProperty(crumbField, crumbValue);
                }
                con.setDoOutput(true);
                // this tells HttpURLConnection not to buffer the whole thing
                con.setFixedLengthStreamingMode((int) tmpFile.length());
                con.connect();
                // send the data
                try (InputStream in = Files.newInputStream(tmpFile.toPath())) {
                    org.apache.commons.io.IOUtils.copy(in, con.getOutputStream());
                } catch (InvalidPathException e) {
                    throw new IOException(e);
                }

                if (con.getResponseCode() != 200) {
                    org.apache.commons.io.IOUtils.copy(con.getErrorStream(), System.err);
                }

                return ret;
            } catch (HttpRetryException e) {
                if (e.getLocation() != null) {
                    // retry with the new location
                    location = new URL(e.getLocation());
                    continue;
                }
                // otherwise failed for reasons beyond us.
                throw e;
            }
        }
    } finally {
        tmpFile.delete();
    }
}

From source file:com.easy.facebook.android.util.Util.java

public static byte[] loadPicture(String urlPicture) {
    byte[] pictureData = null;

    try {/*  w  w w  .  ja  v  a2 s. c om*/
        URL uploadFileUrl = null;
        try {
            uploadFileUrl = new URL(urlPicture);
        } catch (Exception e) {
            e.printStackTrace();
        }

        HttpURLConnection conn = (HttpURLConnection) uploadFileUrl.openConnection();
        conn.setDoInput(true);
        conn.connect();
        InputStream fis = null;
        try {
            fis = conn.getInputStream();
        } catch (IOException e) {

            e.printStackTrace();
        }
        Bitmap bi = BitmapFactory.decodeStream(fis);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bi.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        pictureData = baos.toByteArray();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {

        e.printStackTrace();
    }

    return pictureData;
}

From source file:com.wisdombud.right.client.common.HttpKit.java

/**
 * Send GET request/*ww w.j av a2  s.  c  om*/
 */
public static String get(String url, Map<String, String> queryParas, Map<String, String> headers) {
    HttpURLConnection conn = null;
    try {
        conn = getHttpConnection(buildUrlWithQueryString(url, queryParas), GET, headers);
        conn.connect();
        return readResponseString(conn);
    } catch (final Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:com.uksf.mf.core.utility.ClassNames.java

/**
 * Checks if connection to URL can be established
 * @param url url to check/*from   w w  w. j ava2s . com*/
 * @return connection state
 * @throws IOException error
 */
private static boolean checkConnection(URL url) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.setConnectTimeout(1500);
    connection.setReadTimeout(1500);
    connection.setRequestProperty("User-Agent",
            "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)");
    connection.connect();
    return connection.getResponseCode() == 404;
}

From source file:com.wisdombud.right.client.common.HttpKit.java

/**
 * Send POST request/*from  w  w  w  .j  a v a  2 s  .  c  om*/
 */
public static String post(String url, Map<String, String> queryParas, String data,
        Map<String, String> headers) {
    HttpURLConnection conn = null;
    try {
        conn = getHttpConnection(buildUrlWithQueryString(url, queryParas), POST, headers);
        conn.connect();

        final OutputStream out = conn.getOutputStream();
        out.write(data != null ? data.getBytes(CHARSET) : null);
        out.flush();
        out.close();

        return readResponseString(conn);
    } catch (final Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:Main.java

/**
 * Make an HTTP request to the given URL and return a String as the response.
 *//* w ww. j  a v a  2  s .c o m*/
private static String makeHttpRequest(URL url) throws IOException {
    String jsonResponse = "";

    // If the URL is null, then return early.
    if (url == null) {
        return jsonResponse;
    }

    HttpURLConnection urlConnection = null;
    InputStream inputStream = null;
    try {
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setReadTimeout(10000 /* milliseconds */);
        urlConnection.setConnectTimeout(15000 /* milliseconds */);
        urlConnection.setRequestMethod("GET");
        urlConnection.connect();

        /*
        If the request was successful (response code 200),
        then read the input stream and parse the response.
         */
        if (urlConnection.getResponseCode() == 200) {
            inputStream = urlConnection.getInputStream();
            jsonResponse = readFromStream(inputStream);
        } else {
            //handle exception
        }
    } catch (IOException e) {
        //handle exception
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (inputStream != null) {
            inputStream.close();
        }
    }
    return jsonResponse;
}

From source file:Main.java

/**
 * Given a string url, connects and returns response code
 *
 * @param urlString       string to fetch
 * @param network       network/*from   ww  w . j  a  va2 s .co  m*/
 * @param readTimeOutMs       read time out
 * @param connectionTimeOutMs       connection time out
 * @param urlRedirect       should use urlRedirect
 * @param useCaches       should use cache
 * @return httpResponseCode http response code
 * @throws IOException
 */

@TargetApi(LOLLIPOP)
public static int checkUrlWithOptionsOverNetwork(String urlString, Network network, int readTimeOutMs,
        int connectionTimeOutMs, boolean urlRedirect, boolean useCaches) throws IOException {
    if (network == null) {
        return -1;
    }
    URL url = new URL(urlString);
    HttpURLConnection connection = (HttpURLConnection) network.openConnection(url);
    connection.setReadTimeout(readTimeOutMs /* milliseconds */);
    connection.setConnectTimeout(connectionTimeOutMs /* milliseconds */);
    connection.setRequestMethod("GET");
    connection.setInstanceFollowRedirects(urlRedirect);
    connection.setUseCaches(useCaches);
    // Starts the query
    connection.connect();
    int responseCode = connection.getResponseCode();
    connection.disconnect();
    return responseCode;
}