Java HttpURLConnection Create getHttpConnection(URL url, int expectedResponseCode, int connectionTimeout)

Here you can find the source of getHttpConnection(URL url, int expectedResponseCode, int connectionTimeout)

Description

This method creates a connection to a webpage and then reutrns the connection

License

Apache License

Parameter

Parameter Description
url The Http Address to connect to
expectedResponseCode The expected response code to wait for
connectionTimeout The timeout in seconds

Return

The connection to the http address

Declaration

public static HttpURLConnection getHttpConnection(URL url, int expectedResponseCode, int connectionTimeout)
        throws IOException, ProtocolException 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.io.IOException;

import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;

public class Main {
    /**/*from ww w .  java  2 s  .c om*/
     * This method creates a connection to a webpage and then reutrns the connection
     * 
     * @param url The Http Address to connect to
     * @param expectedResponseCode The expected response code to wait for
     * @param connectionTimeout The timeout in seconds
     * @return The connection to the http address
     */
    public static HttpURLConnection getHttpConnection(URL url, int expectedResponseCode, int connectionTimeout)
            throws IOException, ProtocolException {
        int count = 0;
        HttpURLConnection con = null;
        do {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                //swallow the InterruptedException if there is one
            }
            con = getHttpConnection(url);
            con.connect();
            count++;
        } while (con.getResponseCode() != expectedResponseCode && count < connectionTimeout);
        return con;
    }

    /**
     * This gets an HttpURLConnection to the requested address
     * 
     * @param url The URL to get a connection to
     * @return
     * @throws IOException
     * @throws ProtocolException
     */
    private static HttpURLConnection getHttpConnection(URL url) throws IOException, ProtocolException {
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setDoInput(true);
        con.setDoOutput(true);
        con.setUseCaches(false);
        con.setRequestMethod("GET");
        return con;
    }
}

Related

  1. getHttpConnection(Proxy prx, URL u, int millis)
  2. getHttpConnection(String urlStr, Proxy proxy)
  3. getHttpConnection(String urlStr, String charSet, Map props)
  4. getHTTPConnection(String urlString)
  5. getHttpConnection(URL url)
  6. getHttpURLConnection(@Nonnull String urlStr)
  7. getHttpURLConnection(String postUrl)
  8. getHttpURLConnection(String strUrl)
  9. getHttpURLConnection(String uri, String soapAction, boolean soap12)