Example usage for java.net HttpURLConnection setInstanceFollowRedirects

List of usage examples for java.net HttpURLConnection setInstanceFollowRedirects

Introduction

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

Prototype

public void setInstanceFollowRedirects(boolean followRedirects) 

Source Link

Document

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

Usage

From source file:com.romeikat.datamessie.core.base.service.download.AbstractDownloader.java

protected URLConnection getConnection(final String url) throws IOException {
    final URLConnection urlConnection = new URL(url).openConnection();
    if (urlConnection instanceof HttpURLConnection) {
        final HttpURLConnection httpUrlConnection = (HttpURLConnection) urlConnection;
        httpUrlConnection.setInstanceFollowRedirects(true);
    }//from  w w  w.  j  av  a2s . c o  m
    urlConnection.setConnectTimeout(timeout);
    urlConnection.setReadTimeout(timeout);
    urlConnection.setRequestProperty("User-Agent", userAgent);
    return urlConnection;
}

From source file:pkg4.pkg0.ChildThread.java

void Post() {

    try {/*from w  ww. ja  va 2  s.  c o  m*/

        byte[] postData = body.getBytes(StandardCharsets.UTF_8);
        int postDataLength = postData.length;

        URL url1 = new URL(url);
        HttpURLConnection con = (HttpURLConnection) url1.openConnection();
        con.setDoOutput(true);
        con.setInstanceFollowRedirects(true);
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", " application/json; charset=UTF-8");
        con.setRequestProperty("charset", "utf-8");
        con.setRequestProperty("Content-Length", Integer.toString(postDataLength));
        con.setRequestProperty("User-Agent",
                " Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36");
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
        con.setRequestProperty("Host", host);
        con.setRequestProperty("Cookie", Cookie);
        con.setUseCaches(false);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.write(postData);
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response1 = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response1.append(inputLine);
        }
        String resp = response1.toString();
        in.close();
    } catch (Exception m) {
        m.getMessage();
    }
}

From source file:it.polimi.chansonnier.agent.YoutubeGrabber.java

private String getRedirUrl(String url) {
    String hdr = "";
    try {/*from   ww w  .  jav  a2  s.com*/
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setInstanceFollowRedirects(false);
        conn.addRequestProperty("User-Agent",
                "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.8) Gecko/20100215 Ubuntu/9.04 (jaunty) Shiretoko/3.5.8");
        hdr = conn.getHeaderField("location");
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
    return hdr;
}

From source file:org.wso2.carbon.connector.powerbi.auth.PowerBIAccessTokenGenerator.java

/**
 * Method use to write the request.//from w w  w  . j a v a 2s  . co  m
 *
 * @param endPoint
 *           End point to retrieve access token.
 * @param httpMethod
 *           Method type for HTTP call.
 * @param contentType
 *           Content type of the method call.
 * @param requestQuery
 *           Parameters for method call.
 * @return HttpURLConnection httpUrlConnection object.
 * @throws IOException
 *            If an error occurs on PowerBI API end.
 */
private HttpURLConnection writeRequest(String endPoint, String httpMethod, String contentType,
        String requestQuery) throws IOException {

    OutputStream output = null;

    URL url = new URL(endPoint);
    HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
    httpConnection.setInstanceFollowRedirects(false);
    httpConnection.setRequestMethod(httpMethod);
    httpConnection.setRequestProperty("Content-Type", contentType);
    httpConnection.setDoOutput(true);
    try {

        output = httpConnection.getOutputStream();
        output.write(requestQuery.getBytes(Charset.defaultCharset()));

    } finally {

        if (output != null) {
            try {
                output.close();
            } catch (IOException ioException) {
                log.error("Failed to contact server:", ioException);
            }
        }

    }
    return httpConnection;
}

From source file:org.codehaus.mojo.jboss.AbstractJBossDeployerMojo.java

/**
 * Open a URL.//from   w  w  w  .j a v a  2 s.  c  om
 * 
 * @param url
 * @throws MojoExecutionException
 */
protected void doURL(String url) throws MojoExecutionException {
    try {

        url = url.replaceAll("\\s", "%20");

        getLog().debug("url = " + url);

        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setInstanceFollowRedirects(false);
        connection.setRequestProperty("Authorization", toAuthorization());

        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        reader.readLine();
        reader.close();
    } catch (Exception e) {
        throw new MojoExecutionException("Mojo error occurred: " + e.getMessage(), e);
    }
}

From source file:de.wpsverlinden.otrsspy.OtrsSpy.java

private String probeQueue(int i) throws MalformedURLException, IOException {
    URL url = new URL(host + "index.pl?Action=AgentTicketQueue;QueueID=" + i + ";View=");
    logger.debug("Sending probe request " + url.toString());
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setInstanceFollowRedirects(false);
    conn.setRequestProperty("Cookie", "Session=" + session);
    logger.debug("Receiving logout reply " + conn.getResponseCode());
    return convertToString(conn.getInputStream());
}

From source file:de.wpsverlinden.otrsspy.OtrsSpy.java

private void logout() throws MalformedURLException, IOException {
    URL url = new URL(host + "index.pl?Action=Logout;ChallengeToken=" + logoutToken + ";");
    logger.info("Logout... ");
    logger.debug("Sending logout request " + url.toString());
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setInstanceFollowRedirects(false);
    conn.setRequestProperty("Cookie", "Session=" + session);
    logger.debug("Receiving logout reply " + conn.getResponseCode());
}

From source file:org.apache.hadoop.mapreduce.v2.app.webapp.TestAMWebApp.java

@Test
public void testMRWebAppRedirection() throws Exception {

    String[] schemePrefix = { WebAppUtils.HTTP_PREFIX, WebAppUtils.HTTPS_PREFIX };
    for (String scheme : schemePrefix) {
        MRApp app = new MRApp(2, 2, true, this.getClass().getName(), true) {
            @Override/* ww w .j a  va 2s . co  m*/
            protected ClientService createClientService(AppContext context) {
                return new MRClientService(context);
            }
        };
        Configuration conf = new Configuration();
        conf.set(YarnConfiguration.PROXY_ADDRESS, "9.9.9.9");
        conf.set(YarnConfiguration.YARN_HTTP_POLICY_KEY,
                scheme.equals(WebAppUtils.HTTPS_PREFIX) ? Policy.HTTPS_ONLY.name() : Policy.HTTP_ONLY.name());
        webProxyBase = "/proxy/" + app.getAppID();
        conf.set("hadoop.http.filter.initializers", TestAMFilterInitializer.class.getName());
        Job job = app.submit(conf);
        String hostPort = NetUtils
                .getHostPortString(((MRClientService) app.getClientService()).getWebApp().getListenerAddress());
        URL httpUrl = new URL("http://" + hostPort + "/mapreduce");

        HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
        conn.setInstanceFollowRedirects(false);
        conn.connect();
        String expectedURL = scheme + conf.get(YarnConfiguration.PROXY_ADDRESS)
                + ProxyUriUtils.getPath(app.getAppID(), "/mapreduce");
        Assert.assertEquals(expectedURL, conn.getHeaderField(HttpHeaders.LOCATION));
        Assert.assertEquals(HttpStatus.SC_MOVED_TEMPORARILY, conn.getResponseCode());
        app.waitForState(job, JobState.SUCCEEDED);
        app.verifyCompleted();
    }
}

From source file:org.jumpmind.symmetric.transport.http.HttpIncomingTransport.java

/**
 * This method support redirection from an http connection to an https connection.
 * See {@link http://java.sun.com/j2se/1.4.2/docs/guide/deployment/deployment-guide/upgrade-guide/article-17.html}
 * for more information.//  w w  w . j a  va2s.c o m
 * 
 * @param connection
 * @return
 * @throws IOException
 */
private HttpURLConnection openConnectionCheckRedirects(HttpURLConnection connection) throws IOException {
    boolean redir;
    int redirects = 0;
    do {
        connection.setInstanceFollowRedirects(false);
        redir = false;
        int stat = connection.getResponseCode();
        if (stat >= 300 && stat <= 307 && stat != 306 && stat != HttpURLConnection.HTTP_NOT_MODIFIED) {
            URL base = connection.getURL();
            redirectionUrl = connection.getHeaderField("Location");

            URL target = null;
            if (redirectionUrl != null) {
                target = new URL(base, redirectionUrl);
            }
            connection.disconnect();
            // Redirection should be allowed only for HTTP and HTTPS
            // and should be limited to 5 redirections at most.
            if (target == null || !(target.getProtocol().equals("http") || target.getProtocol().equals("https"))
                    || redirects >= 5) {
                throw new SecurityException("illegal URL redirect");
            }
            redir = true;
            connection = HttpTransportManager.openConnection(target, getBasicAuthUsername(),
                    getBasicAuthPassword());
            connection.setConnectTimeout(httpTimeout);
            connection.setReadTimeout(httpTimeout);

            redirects++;
        }
    } while (redir);

    return connection;
}

From source file:de.wpsverlinden.otrsspy.OtrsSpy.java

private void login() throws MalformedURLException, IOException, ExtractException {
    logger.info("Login...");
    HttpURLConnection conn = (HttpURLConnection) (new URL(host + "index.pl")).openConnection();
    conn.setRequestMethod("POST");
    conn.setInstanceFollowRedirects(false);
    conn.setDoOutput(true);/*  w  w  w.  j a  v  a2  s .  c  o m*/
    try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
        wr.writeBytes("Action=Login&RequestedURL=&Lang=" + lang + "&TimeOffset=-120&User=" + user + "&Password="
                + password);
        wr.flush();
    }
    session = extractSession(conn);
}