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.flozano.socialauth.util.HttpUtil.java

/**
 * Makes HTTP request using java.net.HTTPURLConnection and optional settings
 * for the connection/*from w  ww . j a  va2s . c  o  m*/
 *
 * @param urlStr
 *            the URL String
 * @param requestMethod
 *            Method type
 * @param body
 *            Body to pass in request.
 * @param header
 *            Header parameters
 * @param connectionSettings
 *            The connection settings to apply
 * @return Response Object
 * @throws SocialAuthException
 */
public static Response doHttpRequest(final String urlStr, final String requestMethod, final String body,
        final Map<String, String> header, Optional<ConnectionSettings> connectionSettings)
        throws SocialAuthException {
    HttpURLConnection conn;
    try {

        URL url = new URL(urlStr);
        if (proxyObj != null) {
            conn = (HttpURLConnection) url.openConnection(proxyObj);
        } else {
            conn = (HttpURLConnection) url.openConnection();
        }

        connectionSettings.ifPresent(settings -> settings.apply(conn));

        if (MethodType.POST.toString().equalsIgnoreCase(requestMethod)
                || MethodType.PUT.toString().equalsIgnoreCase(requestMethod)) {
            conn.setDoOutput(true);
        }

        conn.setDoInput(true);

        conn.setInstanceFollowRedirects(true);
        if (timeoutValue > 0) {
            LOG.debug("Setting connection timeout : " + timeoutValue);
            conn.setConnectTimeout(timeoutValue);
        }
        if (requestMethod != null) {
            conn.setRequestMethod(requestMethod);
        }
        if (header != null) {
            for (String key : header.keySet()) {
                conn.setRequestProperty(key, header.get(key));
            }
        }

        // If use POST or PUT must use this
        OutputStream os = null;
        if (body != null) {
            if (requestMethod != null && !MethodType.GET.toString().equals(requestMethod)
                    && !MethodType.DELETE.toString().equals(requestMethod)) {
                os = conn.getOutputStream();
                DataOutputStream out = new DataOutputStream(os);
                out.write(body.getBytes("UTF-8"));
                out.flush();
            }
        }
        conn.connect();
    } catch (Exception e) {
        throw new SocialAuthException(e);
    }
    return new Response(conn);

}

From source file:edu.rit.chrisbitler.ritcraft.slackintegration.SlackIntegration.java

private void startRTM() throws IOException, URISyntaxException, DeploymentException {
    URL url = new URL("https://www.slack.com/api/rtm.start?token=" + BOT_TOKEN);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setInstanceFollowRedirects(true);
    conn.connect();//from   w w w.j  av a 2s.c o m
    JSONObject returnVal = (JSONObject) JSONValue.parse(new InputStreamReader((InputStream) conn.getContent()));
    String wsUrl = (String) returnVal.get("url");

    //unescape the wsUrl string's slashes
    wsUrl = wsUrl.replace("\\", "");

    //Query the users so we can link user id -> username
    System.out.println("Querying slack users..");
    UserList.queryUsers();

    System.out.println("Recieved WebSocket URI from slack, connecting... " + wsUrl);

    //Connect via the real-time messaging client and the websocket.
    ClientEndpointConfig cec = ClientEndpointConfig.Builder.create().build();
    client = ClientManager.createClient();
    rtm = new RTMClient();
    client.connectToServer(rtm, cec, new URI(wsUrl));
}

From source file:org.exoplatform.utils.image.ExoPicassoDownloader.java

@Override
public Response load(Uri uri, int networkPolicy) throws IOException {
    // TODO use networkPolicy as in com.squareup.picasso.UrlConnectionDownloader
    // https://github.com/square/picasso/blob/picasso-parent-2.5.2/picasso/src/main/java/com/squareup/picasso/UrlConnectionDownloader.java
    HttpURLConnection connection = connection(uri);
    connection.setInstanceFollowRedirects(true);
    connection.setUseCaches(true);/*  ww  w.j a  va2 s .  c  o  m*/

    int responseCode = connection.getResponseCode();
    // Handle HTTP redirections that are not managed by HttpURLConnection
    // automatically, e.g. HTTP -> HTTPS
    // TODO consider using OkHttp instead
    if (responseCode >= 300 && responseCode < 400) {
        String location = connection.getHeaderField("Location");
        connection.disconnect();
        connection = connection(Uri.parse(location));
        connection.setInstanceFollowRedirects(true);
        connection.setUseCaches(true);
        responseCode = connection.getResponseCode();
    }
    // Either the original or the new request have failed -> error
    if (responseCode >= 300) {
        connection.disconnect();
        throw new ResponseException(responseCode + " " + connection.getResponseMessage(), networkPolicy,
                responseCode);
    }

    long contentLength = connection.getHeaderFieldInt("Content-Length", -1);
    // boolean fromCache =
    // parseResponseSourceHeader(connection.getHeaderField(RESPONSE_SOURCE));
    boolean fromCache = false;

    return new Response(connection.getInputStream(), fromCache, contentLength);
}

From source file:org.mojohaus.plugins.site.MojohausPluginsMacro.java

private String getFinalUrl(String url) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setInstanceFollowRedirects(false);
    conn.connect();/*from w w w .  j  a va  2 s  .co m*/
    conn.getInputStream();
    if (conn.getResponseCode() == 301 || conn.getResponseCode() == 302) {
        String redirectUrl = conn.getHeaderField("Location");
        return getFinalUrl(redirectUrl);
    }
    return url;
}

From source file:jails.http.client.SimpleClientHttpRequestFactory.java

/**
 * Template method for preparing the given {@link HttpURLConnection}.
 * <p>The default implementation prepares the connection for input and output, and sets the HTTP method.
 *
 * @param connection the connection to prepare
 * @param httpMethod the HTTP request method ({@code GET}, {@code POST}, etc.)
 * @throws IOException in case of I/O errors
 */// w w  w  .  j a v  a 2 s. co  m
protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
    connection.setDoInput(true);
    if ("GET".equals(httpMethod)) {
        connection.setInstanceFollowRedirects(true);
    } else {
        connection.setInstanceFollowRedirects(false);
    }
    if ("PUT".equals(httpMethod) || "POST".equals(httpMethod)) {
        connection.setDoOutput(true);
    } else {
        connection.setDoOutput(false);
    }
    connection.setRequestMethod(httpMethod);
}

From source file:com.codegarden.nativenavigation.JuceActivity.java

public static final HTTPStream createHTTPStream(String address, boolean isPost, byte[] postData, String headers,
        int timeOutMs, int[] statusCode, StringBuffer responseHeaders, int numRedirectsToFollow,
        String httpRequestCmd) {//w w w  .  j  ava2 s  . co m
    // timeout parameter of zero for HttpUrlConnection is a blocking connect (negative value for juce::URL)
    if (timeOutMs < 0)
        timeOutMs = 0;
    else if (timeOutMs == 0)
        timeOutMs = 30000;

    // headers - if not empty, this string is appended onto the headers that are used for the request. It must therefore be a valid set of HTML header directives, separated by newlines.
    // So convert headers string to an array, with an element for each line
    String headerLines[] = headers.split("\\n");

    for (;;) {
        try {
            HttpURLConnection connection = (HttpURLConnection) (new URL(address).openConnection());

            if (connection != null) {
                try {
                    connection.setInstanceFollowRedirects(false);
                    connection.setConnectTimeout(timeOutMs);
                    connection.setReadTimeout(timeOutMs);

                    // Set request headers
                    for (int i = 0; i < headerLines.length; ++i) {
                        int pos = headerLines[i].indexOf(":");

                        if (pos > 0 && pos < headerLines[i].length()) {
                            String field = headerLines[i].substring(0, pos);
                            String value = headerLines[i].substring(pos + 1);

                            if (value.length() > 0)
                                connection.setRequestProperty(field, value);
                        }
                    }

                    connection.setRequestMethod(httpRequestCmd);
                    if (isPost) {
                        connection.setDoOutput(true);

                        if (postData != null) {
                            OutputStream out = connection.getOutputStream();
                            out.write(postData);
                            out.flush();
                        }
                    }

                    HTTPStream httpStream = new HTTPStream(connection, statusCode, responseHeaders);

                    // Process redirect & continue as necessary
                    int status = statusCode[0];

                    if (--numRedirectsToFollow >= 0
                            && (status == 301 || status == 302 || status == 303 || status == 307)) {
                        // Assumes only one occurrence of "Location"
                        int pos1 = responseHeaders.indexOf("Location:") + 10;
                        int pos2 = responseHeaders.indexOf("\n", pos1);

                        if (pos2 > pos1) {
                            String newLocation = responseHeaders.substring(pos1, pos2);
                            // Handle newLocation whether it's absolute or relative
                            URL baseUrl = new URL(address);
                            URL newUrl = new URL(baseUrl, newLocation);
                            String transformedNewLocation = newUrl.toString();

                            if (transformedNewLocation != address) {
                                address = transformedNewLocation;
                                // Clear responseHeaders before next iteration
                                responseHeaders.delete(0, responseHeaders.length());
                                continue;
                            }
                        }
                    }

                    return httpStream;
                } catch (Throwable e) {
                    connection.disconnect();
                }
            }
        } catch (Throwable e) {
        }

        return null;
    }
}

From source file:com.flozano.socialauth.util.HttpUtil.java

/**
 *
 * @param urlStr//from w w w .  j a va 2 s .c  o m
 *            the URL String
 * @param requestMethod
 *            Method type
 * @param params
 *            Parameters to pass in request
 * @param header
 *            Header parameters
 * @param inputStream
 *            Input stream of image
 * @param fileName
 *            Image file name
 * @param fileParamName
 *            Image Filename parameter. It requires in some provider.
 * @return Response object
 * @throws SocialAuthException
 */
public static Response doHttpRequest(final String urlStr, final String requestMethod,
        final Map<String, String> params, final Map<String, String> header, final InputStream inputStream,
        final String fileName, final String fileParamName, Optional<ConnectionSettings> connectionSettings)
        throws SocialAuthException {
    HttpURLConnection conn;
    try {

        URL url = new URL(urlStr);
        if (proxyObj != null) {
            conn = (HttpURLConnection) url.openConnection(proxyObj);
        } else {
            conn = (HttpURLConnection) url.openConnection();
        }

        connectionSettings.ifPresent(settings -> settings.apply(conn));

        if (requestMethod.equalsIgnoreCase(MethodType.POST.toString())
                || requestMethod.equalsIgnoreCase(MethodType.PUT.toString())) {
            conn.setDoOutput(true);
        }

        conn.setDoInput(true);

        conn.setInstanceFollowRedirects(true);
        if (timeoutValue > 0) {
            LOG.debug("Setting connection timeout : " + timeoutValue);
            conn.setConnectTimeout(timeoutValue);
        }
        if (requestMethod != null) {
            conn.setRequestMethod(requestMethod);
        }
        if (header != null) {
            for (String key : header.keySet()) {
                conn.setRequestProperty(key, header.get(key));
            }
        }

        // If use POST or PUT must use this
        OutputStream os = null;
        if (inputStream != null) {
            if (requestMethod != null && !MethodType.GET.toString().equals(requestMethod)
                    && !MethodType.DELETE.toString().equals(requestMethod)) {
                LOG.debug(requestMethod + " request");
                String boundary = "----Socialauth-posting" + System.currentTimeMillis();
                conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
                boundary = "--" + boundary;

                os = conn.getOutputStream();
                DataOutputStream out = new DataOutputStream(os);
                write(out, boundary + "\r\n");

                if (fileParamName != null) {
                    write(out, "Content-Disposition: form-data; name=\"" + fileParamName + "\"; filename=\""
                            + fileName + "\"\r\n");
                } else {
                    write(out, "Content-Disposition: form-data;  filename=\"" + fileName + "\"\r\n");
                }
                write(out, "Content-Type: " + "multipart/form-data" + "\r\n\r\n");
                int b;
                while ((b = inputStream.read()) != -1) {
                    out.write(b);
                }
                // out.write(imageFile);
                write(out, "\r\n");

                Iterator<Map.Entry<String, String>> entries = params.entrySet().iterator();
                while (entries.hasNext()) {
                    Map.Entry<String, String> entry = entries.next();
                    write(out, boundary + "\r\n");
                    write(out, "Content-Disposition: form-data; name=\"" + entry.getKey() + "\"\r\n\r\n");
                    // write(out,
                    // "Content-Type: text/plain;charset=UTF-8 \r\n\r\n");
                    LOG.debug(entry.getValue());
                    out.write(entry.getValue().getBytes("UTF-8"));
                    write(out, "\r\n");
                }

                write(out, boundary + "--\r\n");
                write(out, "\r\n");
            }
        }
        conn.connect();
    } catch (Exception e) {
        throw new SocialAuthException(e);
    }
    return new Response(conn);

}

From source file:org.apache.axis.utils.XMLUtils.java

/**
 * Utility to get the bytes at a protected uri
 *
 * This will retrieve the URL if a username and password are provided.
 * The java.net.URL class does not do Basic Authentication, so we have to
 * do it manually in this routine.//from  ww  w.java  2 s .c o m
 *
 * If no username is provided, we create an InputSource from the uri
 * and let the InputSource go fetch the contents.
 *
 * @param uri the resource to get
 * @param username basic auth username
 * @param password basic auth password
 */
private static InputSource getInputSourceFromURI(String uri, String username, String password)
        throws IOException, ProtocolException, UnsupportedEncodingException {
    URL wsdlurl = null;
    try {
        wsdlurl = new URL(uri);
    } catch (MalformedURLException e) {
        // we can't process it, it might be a 'simple' foo.wsdl
        // let InputSource deal with it
        return new InputSource(uri);
    }

    // if no authentication, just let InputSource deal with it
    if (username == null && wsdlurl.getUserInfo() == null) {
        return new InputSource(uri);
    }

    // if this is not an HTTP{S} url, let InputSource deal with it
    if (!wsdlurl.getProtocol().startsWith("http")) {
        return new InputSource(uri);
    }

    URLConnection connection = wsdlurl.openConnection();
    // Does this work for https???
    if (!(connection instanceof HttpURLConnection)) {
        // can't do http with this URL, let InputSource deal with it
        return new InputSource(uri);
    }
    HttpURLConnection uconn = (HttpURLConnection) connection;
    String userinfo = wsdlurl.getUserInfo();
    uconn.setRequestMethod("GET");
    uconn.setAllowUserInteraction(false);
    uconn.setDefaultUseCaches(false);
    uconn.setDoInput(true);
    uconn.setDoOutput(false);
    uconn.setInstanceFollowRedirects(true);
    uconn.setUseCaches(false);

    // username/password info in the URL overrides passed in values
    String auth = null;
    if (userinfo != null) {
        auth = userinfo;
    } else if (username != null) {
        auth = (password == null) ? username : username + ":" + password;
    }

    if (auth != null) {
        uconn.setRequestProperty("Authorization", "Basic " + base64encode(auth.getBytes(httpAuthCharEncoding)));
    }

    uconn.connect();

    return new InputSource(uconn.getInputStream());
}

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

protected String getResponseUrl(final URLConnection urlConnection) throws IOException {
    if (!(urlConnection instanceof HttpURLConnection)) {
        return urlConnection.getURL().toExternalForm();
    }//from  w  w  w  .  j av  a2s  . c o m
    final HttpURLConnection httpUrlConnection = (HttpURLConnection) urlConnection;
    httpUrlConnection.setInstanceFollowRedirects(false);
    final String responseUrl = httpUrlConnection.getHeaderField("Location");
    return responseUrl;
}

From source file:pkg4.pkg0.ChildThread.java

void Get() {
    try {/*from   w w w.j  a v a  2 s .  c  om*/

        URL url1 = new URL(url);
        HttpURLConnection con = (HttpURLConnection) url1.openConnection();
        con.setDoOutput(true);
        con.setInstanceFollowRedirects(true);
        con.setRequestMethod("GET");
        con.setRequestProperty("Content-Type", " application/json; charset=UTF-8");
        con.setRequestProperty("charset", "utf-8");
        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());
        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) {

    }
}