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:com.microsoft.azuretools.utils.WebAppUtils.java

public static boolean isUrlAccessible(String url) throws IOException {
    HttpURLConnection.setFollowRedirects(false);
    HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
    con.setRequestMethod("HEAD");
    con.setReadTimeout(Constants.connection_read_timeout_ms);
    try {/*from  ww w.j av a 2s  .c  o  m*/
        if (con.getResponseCode() != HttpURLConnection.HTTP_OK) {
            return false;
        }
    } catch (IOException ex) {
        return false;
    }
    return true;
}

From source file:com.ibm.caas.CaaSResource.java

/**
 * Fetch content from MACM instance by doing a HTTP GET request and set
 * Cookies/*w  w  w .ja va2s  .c o  m*/
 * 
 * @param url
 *            {@link String} MACM content url
 * @return {@link InputStream}
 */
public InputStream openStream(String url) throws IOException {

    urlConnection = (HttpURLConnection) new URL(url).openConnection();
    urlConnection.setRequestMethod("GET");
    urlConnection.setUseCaches(false);

    HttpURLConnection.setFollowRedirects(true);

    if (COOKIES != null) {
        for (String cookie : CaaSResource.COOKIES) {
            urlConnection.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
        }
    }

    if (urlConnection.getResponseCode() == 401 || urlConnection.getResponseCode() == 400) {
        try {
            connect();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } finally {
            openStream(url);
        }
    }

    return urlConnection.getInputStream();
}

From source file:JavaTron.AudioTron.java

/**
 * Three parameter version of constructor -- allows setting of AudioTron
 * address, username, and password.//from  w  w w.jav a 2  s .  c  o  m
 *
 * @param server the AudioTron ip address (defaults to 192.168.0.10) 
 * @param username the username to use when accessing AudioTron pages
 *                 (defaults to 'admin')
 * @param password the password to use when accessing the AudioTron pages
 *                 (defaults to 'admin')
 */
public AudioTron(String server, String username, String password) {
    setDefaults();

    if (server != null)
        Configuration.setProperty(Configuration.KEY_SERVER, server);
    if (username != null)
        Configuration.setProperty(Configuration.KEY_USERNAME, username);
    if (password != null)
        Configuration.setProperty(Configuration.KEY_PASSWORD, password);

    // Setup the status mappings
    statusMap.put(new Integer(COMMAND), "Cmd");
    statusMap.put(new Integer(INFO), "Info");
    statusMap.put(new Integer(CLOCK), "Get Clock");
    statusMap.put(new Integer(SET_CLOCK), "Set Clock");
    statusMap.put(new Integer(GLOBAL), "Global");
    statusMap.put(new Integer(TOC), "Save TOC");
    statusMap.put(new Integer(NAP), "Set Nap");
    statusMap.put(new Integer(ALARM), "Set Alarm");
    statusMap.put(new Integer(DELQUE), "Removing");
    statusMap.put(new Integer(ADDNEW), "Adding");
    statusMap.put(new Integer(SEARCH), "Seaching");
    statusMap.put(new Integer(MSG), "Display");
    // Setup the HttpURLConnection class
    HttpURLConnection.setFollowRedirects(false);

    // Fire up the Command processor thread
    commandThread = new CommandThread(this);

    // Fire up the NTP daemon
    new MSNTPDaemon();
}

From source file:fr.lissi.belilif.om2m.rest.WebServiceActions.java

/**
 * Checks if is reachable.//from   w  w w  . j  a v  a2 s .  c  o m
 *
 * @param uri the uri
 * @param headers the headers
 * @return true, if is reachable
 */
public static boolean isReachable(String uri, HashMap<String, String> headers) {
    try {
        HttpURLConnection.setFollowRedirects(false);
        // note : you may also need
        // HttpURLConnection.setInstanceFollowRedirects(false)
        HttpURLConnection myURLConnection = (HttpURLConnection) new URL(uri).openConnection();
        myURLConnection.setRequestMethod("HEAD");
        for (String key : headers.keySet()) {
            myURLConnection.setRequestProperty("Authorization", headers.get(key));
        }
        LOGGER.info(myURLConnection.getResponseCode() + " / " + myURLConnection.toString());
        return (myURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK);
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

From source file:gr.scify.newsum.Utils.java

public static boolean urlChanged(String url) {
    try {/*  w  ww  . j a v  a 2  s .c o  m*/
        HttpURLConnection.setFollowRedirects(false);
        HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
        con.setRequestMethod("HEAD");
        return (con.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED);
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

From source file:co.forsaken.api.json.JsonWebCall.java

private boolean canConnect() throws Exception {
    try {/*from ww  w  . j  a  va 2  s . c  om*/
        HttpURLConnection.setFollowRedirects(false);
        HttpURLConnection con = (HttpURLConnection) new URL(_url).openConnection();
        con.setRequestMethod("HEAD");

        con.setConnectTimeout(2000);

        if (con.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new Exception("Service " + _url + " unavailable, oh no!");
        }
        return true;
    } catch (java.net.SocketTimeoutException e) {
        throw new Exception("Service " + _url + " unavailable, oh no!", e);
    } catch (java.io.IOException e) {
        throw new Exception("Service " + _url + " unavailable, oh no!", e);
    }
}

From source file:gr.scify.newsum.Utils.java

/**
 * Returns the last modified HTTP property of a given URL.
 * @param url The url to examine/*www . ja  v  a  2  s.com*/
 * @return A long number indicating the modified header field
 * of the URL. 
 * @throws IOException If the connection to the URL fails.
 */
public static long lastModified(URL url) throws IOException {
    HttpURLConnection.setFollowRedirects(true);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    long date = con.getLastModified();

    return date;
}

From source file:fr.lissi.belilif.om2m.rest.WebServiceActions.java

/**
 * Checks if a resource is reachable.//from  ww  w. j ava  2s .  c  o m
 *
 * @param uri the uri
 * @return true, if is reachable
 */
public static boolean isReachable(String uri) {
    try {
        HttpURLConnection.setFollowRedirects(false);
        HttpURLConnection myURLConnection = (HttpURLConnection) new URL(uri).openConnection();
        myURLConnection.setRequestMethod("HEAD");
        return (myURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK);
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

From source file:org.zend.sdklib.internal.target.ZendDevCloud.java

/**
 * Wake up a Phpcloud container with specified name.
 * //from www.j av a  2 s. c  o m
 * @param containerName
 * @param username phpcloud account username
 * @param password phpcloud account password
 * @return <code>true</code> if container is awake
 */
public boolean wakeUp(String containerName, String username, String password) throws SdkException {
    boolean orginal = setFollowRedirect();
    SSLContextInitializer.instance.setDefaultSSLFactory();
    try {
        while (true) {
            String json = getJson(authenticate(username, password),
                    "/container/" + containerName + "/overview?format=json");
            PhpcloudContainerStatus status = PhpcloudContainerStatus.byName(getStatus(json, ""));
            if (status == null) {
                break;
            }
            if (status == PhpcloudContainerStatus.RUNNING) {
                return true;
            }
            if (status == PhpcloudContainerStatus.SLEEPING || status == PhpcloudContainerStatus.PROVISIONED) {
                Thread.sleep(5000);
            }
            if (status == PhpcloudContainerStatus.FROZEN) {
                Thread.sleep(10000);
            }
        }
    } catch (InterruptedException e) {
        return wakeUp(containerName, username, password);
    } catch (IOException e) {
        throw new SdkException(e);
    } finally {
        HttpURLConnection.setFollowRedirects(orginal);
        SSLContextInitializer.instance.restoreDefaultSSLFactory();
    }
    return false;
}

From source file:javafxpert.conceptmap.alexa.ConceptMapSpeechlet.java

/**
 * Call a ConceptMap endpoint to retrieve related claims
 *
 * @throws IOException//w w  w .j  a v  a2s. c  o  m
 */
//private SpeechletResponse makeClaimsRequest(String itemId, String propId) {
private SpeechletResponse makeClaimsRequest(String itemValue, String relationshipValue) {
    String properCasedItemValue = WordUtils.capitalize(itemValue);
    String speechOutput = "";
    Image image = new Image();

    // Translate requested item and relationship to Q and P numbers
    //String itemId = "Q887401";
    String propId = "P54";
    String itemId = locateItemId(properCasedItemValue);
    if (itemId != null && itemId.length() > 0) {

        String queryString = String.format("?id=%s&direction=f&prop=%s&depth=1", itemId, propId);

        InputStreamReader inputStream = null;
        BufferedReader bufferedReader = null;
        StringBuilder builder = new StringBuilder();
        try {
            String line;
            URL url = new URL(TRAVERSAL_ENDPOINT + queryString);
            inputStream = new InputStreamReader(url.openStream(), Charset.forName("US-ASCII"));
            bufferedReader = new BufferedReader(inputStream);
            while ((line = bufferedReader.readLine()) != null) {
                builder.append(line);
            }
        } catch (IOException e) {
            // reset builder to a blank string
            builder.setLength(0);
        } finally {
            IOUtils.closeQuietly(inputStream);
            IOUtils.closeQuietly(bufferedReader);

            log.info("builder: " + builder);
        }

        if (builder.length() == 0) {
            speechOutput = "Sorry, the Concept Map claims service is experiencing a problem. "
                    + "Please try again later.";
        } else {
            try {
                JSONObject claimsResponseObject = new JSONObject(new JSONTokener(builder.toString()));

                if (claimsResponseObject != null) {
                    ClaimsInfo claimsInfo = createClaimsInfo(claimsResponseObject, itemId);

                    log.info("claimsInfo: " + claimsInfo);

                    speechOutput = "Item " + properCasedItemValue + " not found";

                    if (claimsInfo.getItemLabels().size() > 0) {
                        speechOutput = new StringBuilder().append(properCasedItemValue)
                                //.append(claimsInfo.getItemLabels().get(0))
                                .append(" has been a member of ").append(relationshipValue).append(" \n")
                                .append(claimsInfo.toItemLabelsSpeech()).toString();
                    }

                    // Get the picture redirect
                    URL url = new URL(claimsInfo.getPictureUrl());
                    HttpURLConnection.setFollowRedirects(false);
                    final HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    //con.setInstanceFollowRedirects(false);
                    final int responseCode = con.getResponseCode();
                    final String redirectLocation = con.getHeaderField("Location");
                    image.setSmallImageUrl(redirectLocation);
                }
                //} catch (JSONException | ParseException e) {
            } catch (JSONException | IOException e) {
                log.error("Exception occoured while parsing service response.", e);
            }
        }
    } else {
        speechOutput = "Couldn't locate an Item ID for item " + properCasedItemValue;
    }

    // Create the Simple card content.
    StandardCard card = new StandardCard();
    card.setTitle(properCasedItemValue);
    card.setText(speechOutput);
    card.setImage(image);
    // Create the plain text output
    PlainTextOutputSpeech outputSpeech = new PlainTextOutputSpeech();
    outputSpeech.setText(speechOutput);

    return SpeechletResponse.newTellResponse(outputSpeech, card);
}