Example usage for java.net HttpURLConnection setFollowRedirects

List of usage examples for java.net HttpURLConnection setFollowRedirects

Introduction

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

Prototype

public static void setFollowRedirects(boolean set) 

Source Link

Document

Sets whether HTTP redirects (requests with response code 3xx) should be automatically followed by this class.

Usage

From source file:demo.ServerRunning.java

@Override
public Statement apply(final Statement base, FrameworkMethod method, Object target) {

    // Check at the beginning, so this can be used as a static field
    Assume.assumeTrue(serverOnline.get(port));

    RestTemplate client = new RestTemplate();
    boolean followRedirects = HttpURLConnection.getFollowRedirects();
    HttpURLConnection.setFollowRedirects(false);
    boolean online = false;
    try {/*ww  w  .  j a v  a2  s .co  m*/
        client.getForEntity(new UriTemplate(getUrl("/info")).toString(), String.class);
        online = true;
        logger.info("Basic connectivity test passed");
    } catch (RestClientException e) {
        logger.warn(String.format(
                "Not executing tests because basic connectivity test failed for hostName=%s, port=%d", hostName,
                port), e);
        Assume.assumeNoException(e);
    } finally {
        HttpURLConnection.setFollowRedirects(followRedirects);
        if (!online) {
            serverOnline.put(port, false);
        }
    }

    return new Statement() {

        @Override
        public void evaluate() throws Throwable {
            base.evaluate();
        }
    };

}

From source file:org.ut.biolab.medsavant.shared.util.NetworkUtils.java

/**
 * Open a stream for the given URL with custom timeouts
 * @throws IOException//from   ww w.java  2s  . c  om
 */
public static InputStream openStream(URL url, int connectTimeout, int readTimeout)
        throws IOException, SocketTimeoutException {
    //URLConnection conn = url.openConnection();
    // conn.setConnectTimeout(connectTimeout);
    //conn.setReadTimeout(readTimeout);

    HttpURLConnection huc = (HttpURLConnection) url.openConnection();
    HttpURLConnection.setFollowRedirects(ALLOW_URL_REDIRECTS);
    huc.setConnectTimeout(connectTimeout);
    huc.setReadTimeout(readTimeout);
    huc.setRequestMethod("GET");
    huc.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)");
    huc.connect();
    InputStream input = huc.getInputStream();
    return input;
}

From source file:hudson.plugins.memegen.MemegeneratorResponseException.java

public boolean instanceCreate(Meme meme) {
    boolean ret = false;
    HashMap<String, String> vars = new HashMap();
    vars.put("username", username);
    vars.put("password", password);
    vars.put("text0", meme.getUpperText());
    vars.put("text1", meme.getLowerText());
    vars.put("generatorID", "" + meme.getGeneratorID());
    vars.put("imageID", "" + meme.getImageID());

    try {/*  w w  w . j  av  a  2s  .  co  m*/
        URL url = buildURL("Instance_Create", vars);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        HttpURLConnection.setFollowRedirects(true);
        conn.setDoOutput(true);
        JSONObject obj = parseResponse(conn);
        JSONObject result = (JSONObject) obj.get("result");
        String memeUrl = (String) result.get("instanceImageUrl");
        if (memeUrl.matches("^http(.*)") == false) {
            memeUrl = APIURL + memeUrl;
        }
        //Debug the JSON to logs
        //System.err.println(obj.toJSONString()+", AND "+result.toJSONString());
        meme.setImageURL(memeUrl);
        ret = true;

    } catch (MalformedURLException me) {
        String log_warn_prefix = "Memegenerator API malformed URL: ";
        System.err.println(log_warn_prefix.concat(me.getMessage()));
    } catch (IOException ie) {
        String log_warn_prefix = "Memegenerator API IO exception: ";
        System.err.println(log_warn_prefix.concat(ie.getMessage()));
    } catch (ParseException pe) {
        String log_warn_prefix = "Memegenerator API malformed response: ";
        System.err.println(log_warn_prefix.concat(pe.getMessage()));
    } catch (MemegeneratorResponseException mre) {
        String log_warn_prefix = "Memegenerator API failure: ";
        System.err.println(log_warn_prefix.concat(mre.getMessage()));
    } catch (MemegeneratorJSONException mje) {
        String log_warn_prefix = "Memegenerator API malformed JSON: ";
        System.err.println(log_warn_prefix.concat(mje.getMessage()));
    }

    return ret;
}

From source file:eu.liveandgov.ar.utilities.OS_Utils.java

/**      
 * Check if URL exists /* w  w  w.  j  a va 2 s. c  o  m*/
 *        
 * @param urlSTR
 * @return
 */
public static boolean exists(String URLName) {
    try {
        HttpURLConnection.setFollowRedirects(false);
        // note : you may also need
        //        HttpURLConnection.setInstanceFollowRedirects(false)
        HttpURLConnection con = (HttpURLConnection) new URL(URLName).openConnection();
        con.setRequestMethod("HEAD");

        return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
    } catch (Exception e) {

        return false;
    }
}

From source file:org.spoutcraft.client.io.MirrorUtils.java

public static boolean isAddressReachable(String url) {
    try {//from w ww .ja  va 2  s . co m
        URL test = new URL(url);
        HttpURLConnection.setFollowRedirects(false);
        HttpURLConnection urlConnect = (HttpURLConnection) test.openConnection();
        urlConnect.setRequestMethod("HEAD");
        return (urlConnect.getResponseCode() == HttpURLConnection.HTTP_OK);
    } catch (Exception e) {
        return false;
    }
}

From source file:org.spoutcraft.launcher.api.util.Download.java

@SuppressWarnings("unused")
public void run() {
    ReadableByteChannel rbc = null;
    FileOutputStream fos = null;/*from ww  w  . ja va2  s.c o  m*/
    try {
        URLConnection conn = url.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(false);
        System.setProperty("http.agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");
        conn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");
        HttpURLConnection.setFollowRedirects(true);
        conn.setUseCaches(false);
        ((HttpURLConnection) conn).setInstanceFollowRedirects(true);
        int response = ((HttpURLConnection) conn).getResponseCode();
        InputStream in = getConnectionInputStream(conn);

        size = conn.getContentLength();
        outFile = new File(outPath);
        outFile.delete();

        rbc = Channels.newChannel(in);
        fos = new FileOutputStream(outFile);

        stateChanged();

        Thread progress = new MonitorThread(Thread.currentThread(), rbc);
        progress.start();

        fos.getChannel().transferFrom(rbc, 0, size > 0 ? size : Integer.MAX_VALUE);
        in.close();
        rbc.close();
        progress.interrupt();
        if (size > 0) {
            if (size == outFile.length()) {
                result = Result.SUCCESS;
            }
        } else {
            result = Result.SUCCESS;
        }
    } catch (PermissionDeniedException e) {
        result = Result.PERMISSION_DENIED;
    } catch (DownloadException e) {
        result = Result.FAILURE;
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(fos);
        IOUtils.closeQuietly(rbc);
    }
}

From source file:org.spoutcraft.launcher.util.Download.java

@SuppressWarnings("unused")
public void run() {
    ReadableByteChannel rbc = null;
    FileOutputStream fos = null;/*from w  ww  .  ja v  a  2  s  . c o  m*/
    try {
        URLConnection conn = url.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(false);
        System.setProperty("http.agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");
        conn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");
        HttpURLConnection.setFollowRedirects(true);
        conn.setUseCaches(false);
        ((HttpURLConnection) conn).setInstanceFollowRedirects(true);
        int response = ((HttpURLConnection) conn).getResponseCode();
        InputStream in = getConnectionInputStream(conn);

        size = conn.getContentLength();
        outFile = new File(outPath);
        outFile.delete();

        rbc = Channels.newChannel(in);
        fos = new FileOutputStream(outFile);

        stateChanged();

        Thread progress = new MonitorThread(Thread.currentThread(), rbc);
        progress.start();

        fos.getChannel().transferFrom(rbc, 0, size > 0 ? size : Integer.MAX_VALUE);
        in.close();
        rbc.close();
        progress.interrupt();
        if (size > 0) {
            if (size == outFile.length()) {
                result = Result.SUCCESS;
            }
        } else {
            result = Result.SUCCESS;
        }
    } catch (PermissionDeniedException e) {
        exception = e;
        result = Result.PERMISSION_DENIED;
    } catch (DownloadException e) {
        exception = e;
        result = Result.FAILURE;
    } catch (Exception e) {
        exception = e;
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(fos);
        IOUtils.closeQuietly(rbc);
    }
}

From source file:org.jboss.tools.openshift.reddeer.utils.TestUtils.java

/**
 * Finds out whether a URL returns HTTP OK or not.
 * //from   w  w w  . j  av a2s.c  om
 * @param URL URL to find out whether is accessible 
 * @return true if URL is accesible with HTTP OK exit code (200), false otherwise
 */
public static boolean isURLAccessible(String URL) {
    try {
        HttpURLConnection.setFollowRedirects(false);
        HttpURLConnection connection = (HttpURLConnection) new URL(URL).openConnection();
        connection.setRequestMethod("HEAD");
        return (connection.getResponseCode() == HttpURLConnection.HTTP_OK);
    } catch (Exception e) {
        return false;
    }
}

From source file:net.technicpack.launchercore.mirror.MirrorStore.java

public String getETag(String address) {
    String md5 = "";

    try {/*from   ww w . j  a v  a 2s  .  com*/
        URL url = getFullUrl(address);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(false);
        System.setProperty("http.agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");
        conn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");
        HttpURLConnection.setFollowRedirects(true);
        conn.setUseCaches(false);
        conn.setInstanceFollowRedirects(true);

        String eTag = conn.getHeaderField("ETag");
        if (eTag != null) {
            eTag = eTag.replaceAll("^\"|\"$", "");
            if (eTag.length() == 32) {
                md5 = eTag;
            }
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return md5;
}

From source file:org.javaweb.utils.HttpRequestUtils.java

/**
 * HTTP HTTP????User-Agent?Referer//from   w w  w  .  ja v a  2 s  . com
 *
 * @param httpURLConnection
 * @param request
 * @throws IOException
 */
public static void setRequestProperties(HttpURLConnection httpURLConnection, HttpRequest request)
        throws IOException {
    httpURLConnection.setConnectTimeout(request.getTimeout());
    httpURLConnection.setReadTimeout(request.getTimeout());
    HttpURLConnection.setFollowRedirects(request.isFollowRedirects());

    if (StringUtils.isNotEmpty(request.getMethod()) && !(request instanceof MultipartRequest)) {

        // ?GETDoInput?DoOutput
        if (!"GET".equalsIgnoreCase(request.getMethod())) {
            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);
        }

        httpURLConnection.setRequestMethod(request.getMethod().toUpperCase());
    }

    // Cookie
    if (StringUtils.isNotEmpty(request.getCookie())) {
        httpURLConnection.setRequestProperty("Cookie", request.getCookie());
    }

    // User-Agent
    if (StringUtils.isNotEmpty(request.getUserAgent())) {
        httpURLConnection.setRequestProperty("User-Agent", request.getUserAgent());
    }

    // Referer
    if (StringUtils.isNotEmpty(request.getReferer())) {
        httpURLConnection.setRequestProperty("Referer", request.getReferer());
    }
}