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.vaguehope.onosendai.util.HttpHelper.java

private static <R> R fetchWithFollowRedirects(final Method method, final URL url,
        final HttpStreamHandler<R> streamHandler, final int redirectCount)
        throws IOException, URISyntaxException {
    final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    try {/*from   ww  w .  j a  v  a 2 s .  c  om*/
        connection.setRequestMethod(method.toString());
        connection.setInstanceFollowRedirects(false);
        connection.setConnectTimeout((int) TimeUnit.SECONDS.toMillis(HTTP_CONNECT_TIMEOUT_SECONDS));
        connection.setReadTimeout((int) TimeUnit.SECONDS.toMillis(HTTP_READ_TIMEOUT_SECONDS));
        connection.setRequestProperty("User-Agent", "curl/1"); // Make it really clear this is not a browser.
        //connection.setRequestProperty("Accept-Encoding", "identity"); This fixes missing Content-Length headers but feels wrong.
        connection.connect();

        InputStream is = null;
        try {
            final int responseCode = connection.getResponseCode();

            // For some reason some devices do not follow redirects. :(
            if (responseCode == 301 || responseCode == 302 || responseCode == 303 || responseCode == 307) { // NOSONAR not magic numbers.  Its HTTP spec.
                if (redirectCount >= MAX_REDIRECTS)
                    throw new TooManyRedirectsException(responseCode, url, MAX_REDIRECTS);
                final String locationHeader = connection.getHeaderField("Location");
                if (locationHeader == null)
                    throw new HttpResponseException(responseCode,
                            "Location header missing.  Headers present: " + connection.getHeaderFields() + ".");
                connection.disconnect();

                final URL locationUrl;
                if (locationHeader.toLowerCase(Locale.ENGLISH).startsWith("http")) {
                    locationUrl = new URL(locationHeader);
                } else {
                    locationUrl = url.toURI().resolve(locationHeader).toURL();
                }
                return fetchWithFollowRedirects(method, locationUrl, streamHandler, redirectCount + 1);
            }

            if (responseCode < 200 || responseCode >= 300) { // NOSONAR not magic numbers.  Its HTTP spec.
                throw new NotOkResponseException(responseCode, connection, url);
            }

            is = connection.getInputStream();
            final int contentLength = connection.getContentLength();
            if (contentLength < 1)
                LOG.w("Content-Length=%s for %s.", contentLength, url);
            return streamHandler.handleStream(connection, is, contentLength);
        } finally {
            IoHelper.closeQuietly(is);
        }
    } finally {
        connection.disconnect();
    }
}

From source file:org.openbravo.test.datasource.DatasourceTestUtil.java

static HttpURLConnection createConnection(String url, String wsPart, String method, String cookie)
        throws Exception {

    String completeUrl = url + wsPart;
    log.debug("Create conntection URL: {}, method {}", completeUrl, method);
    final URL connUrl = new URL(completeUrl);
    final HttpURLConnection hc = (HttpURLConnection) connUrl.openConnection();
    hc.setRequestMethod(method);/*from w w w  .  j a  v a2s  .c om*/
    hc.setAllowUserInteraction(false);
    hc.setDefaultUseCaches(false);
    hc.setDoOutput(true);
    hc.setDoInput(true);
    hc.setInstanceFollowRedirects(true);
    hc.setUseCaches(false);
    if (cookie != null) {
        hc.setRequestProperty("Cookie", cookie);
    }
    return hc;
}

From source file:com.google.api.ads.adwords.awreporting.server.appengine.exporter.ReportExporterAppEngine.java

public static void html2PdfOverNet(InputStream htmlSource, ReportWriter reportWriter) {
    try {//from   w  w  w.j  a  v  a 2s.c om
        URL url = new URL(HTML_2_PDF_SERVER_URL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setInstanceFollowRedirects(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "text/html");
        connection.setRequestProperty("charset", "utf-8");
        connection.setUseCaches(false);

        DataOutputStream send = new DataOutputStream(connection.getOutputStream());
        send.write(IOUtils.toByteArray(htmlSource));
        send.flush();

        // Read from connection
        reportWriter.write(connection.getInputStream());

        send.close();

        connection.disconnect();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.owasp.dependencycheck.utils.URLConnectionFactory.java

/**
 * Utility method to create an HttpURLConnection. The use of a proxy here is optional as there may be cases where a proxy is
 * configured but we don't want to use it (for example, if there's an internal repository configured)
 *
 * @param url the URL to connect to//  w w w.ja v a2  s. co m
 * @param proxy whether to use the proxy (if configured)
 * @return a newly constructed HttpURLConnection
 * @throws URLConnectionFailureException thrown if there is an exception
 */
public static HttpURLConnection createHttpURLConnection(URL url, boolean proxy)
        throws URLConnectionFailureException {
    if (proxy) {
        return createHttpURLConnection(url);
    }
    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) url.openConnection();
        final int timeout = Settings.getInt(Settings.KEYS.CONNECTION_TIMEOUT, 10000);
        conn.setConnectTimeout(timeout);
        conn.setInstanceFollowRedirects(true);
    } catch (IOException ioe) {
        throw new URLConnectionFailureException("Error getting connection.", ioe);
    }
    return conn;
}

From source file:edu.hackathon.perseus.core.httpSpeedTest.java

public static String getRedirectUrl(REGION region) {
    String result = "";

    switch (region) {
    case EU:/*from www.j ava2s.  c o  m*/
        result = amazonEuDomain;
        break;
    case USA:
        result = amazonUsaDomain;
        break;
    case ASIA:
        result = amazonAsiaDomain;
        break;
    }

    System.out.println("Trying to get real IP address of " + result);
    try {
        /*
        HttpHead headRequest = new HttpHead(result);
        HttpClient client = new DefaultHttpClient();
         HttpResponse response = client.execute(headRequest);
         final int statusCode = response.getStatusLine().getStatusCode();
         if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY ||
             statusCode == HttpStatus.SC_MOVED_TEMPORARILY)
         {
             String location = response.getHeaders("Location")[0].toString();
             String redirecturl = location.replace("Location: ", "");
             result = redirecturl;
         }
        */

        URL url = new URL(result);
        HttpURLConnection httpGetCon = (HttpURLConnection) url.openConnection();
        httpGetCon.setInstanceFollowRedirects(false);
        httpGetCon.setRequestMethod("GET");
        httpGetCon.setConnectTimeout(5000); //set timeout to 5 seconds

        httpGetCon.setRequestProperty("User-Agent", USER_AGENT);

        int status = httpGetCon.getResponseCode();
        System.out.println("code: " + status);
        if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                || status == HttpURLConnection.HTTP_SEE_OTHER)
            result = httpGetCon.getHeaderField("Location");

    } catch (Exception e) {
        System.out.println("Exception is fired in redirector getter. error:" + e.getMessage());
        e.printStackTrace();
    }
    System.out.println("Real IP address is " + result);
    return result;
}

From source file:pt.ist.maidSyncher.api.activeCollab.JsonRest.java

public static Object processPost(String content, String urlStr) throws IOException {
    URL url = new URL(urlStr);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);// ww w.  java2 s.  c  o m
    conn.setDoInput(true);
    conn.setInstanceFollowRedirects(false);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("charset", "utf-8");
    conn.setRequestProperty("Content-Length", "" + Integer.toString(content.getBytes("utf-8").length));
    conn.setUseCaches(false);
    conn.connect();

    //Send request
    DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
    wr.writeBytes(content);
    wr.flush();
    wr.close();

    LOGGER.trace("ACURL [" + url + "]");

    InputStream is = null;
    try {
        is = conn.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("utf-8")));
        String jsonText = readAll(rd);
        return JSONValue.parse(jsonText);
    } catch (IOException ex) {
        int responseCode = conn.getResponseCode();
        if ((responseCode / 100) != 2) {
            InputStream errorStream = conn.getErrorStream();
            try {
                BufferedReader rd = new BufferedReader(
                        new InputStreamReader(errorStream, Charset.forName("utf-8")));
                Gson gsonBuilder = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
                JsonElement jsonErrorBody = new JsonParser().parse(rd);
                LOGGER.error("Error: \n" + gsonBuilder.toJson(jsonErrorBody) + "\nOriginal request body:\n"
                        + content + "\nURL: " + url);
            } finally {
                if (errorStream != null)
                    errorStream.close();
                conn.disconnect();
            }

        }
        throw ex;
    } finally {
        if (is != null)
            is.close();
        conn.disconnect();
    }
}

From source file:mashberry.com500px.util.Api_Parser.java

/*******************************************************************************
  * /*from w  w  w  .  j a va 2 s .com*/
  *    (  )
  * 
  *******************************************************************************/
public static String get_first_detail(final String url_feature, final int url_image_size,
        final String url_category, final int url_page, int image_no) {
    String returnStr = "success";
    String urlStr = DB.Get_Photo_Url + "?feature=" + url_feature + "&image_size=" + url_image_size + "&only="
            + getCategoryName(url_category) + "&page=" + url_page + "&consumer_key=" + Var.consumer_key
            + "&rpp=" + image_no;

    try {
        URL url = new URL(urlStr);
        URLConnection uc = url.openConnection();
        HttpURLConnection httpConn = (HttpURLConnection) uc;
        httpConn.setAllowUserInteraction(false);
        httpConn.setInstanceFollowRedirects(true);
        httpConn.setConnectTimeout(10000);
        httpConn.setRequestMethod("GET");
        httpConn.connect();
        int response = httpConn.getResponseCode();
        Main.progressBar_process(50);

        if (response == HttpURLConnection.HTTP_OK) {
            InputStream in = httpConn.getInputStream();
            String smallImageOpt = "3"; //      (8 1/8  )
            String largeImageOpt = "0";
            String userPictureOpt = "8";
            String result = convertStreamToString(in);
            JSONObject jObject = new JSONObject(result);
            JSONArray jsonArray = jObject.getJSONArray("photos");
            Main.progressBar_process(75);

            if (jsonArray.length() == 0) {
                returnStr = "no results";
            } else {
                for (int i = 0; i < jsonArray.length(); i++) {
                    Var.categoryArr.add(jsonArray.getJSONObject(i).getString("category"));
                    Var.idArr.add(jsonArray.getJSONObject(i).getString("id"));
                    String smallImage = jsonArray.getJSONObject(i).getString("image_url");
                    String largeImage = largeImageOpt
                            + smallImage.substring(0, smallImage.lastIndexOf(".jpg") - 1) + "4.jpg";
                    Var.imageSmall_urlArr.add(smallImageOpt + smallImage);
                    Var.imageLarge_urlArr.add(largeImage);
                    Var.nameArr.add(jsonArray.getJSONObject(i).getString("name"));
                    Var.ratingArr.add(jsonArray.getJSONObject(i).getString("rating"));

                    JSONObject jsonuser = jsonArray.getJSONObject(i).getJSONObject("user");
                    Var.user_firstnameArr.add(jsonuser.getString("firstname"));
                    Var.user_fullnameArr.add(jsonuser.getString("fullname"));
                    Var.user_lastnameArr.add(jsonuser.getString("lastname"));
                    Var.user_upgrade_statusArr.add(jsonuser.getString("upgrade_status"));
                    Var.user_usernameArr.add(jsonuser.getString("username"));
                    Var.user_userpic_urlArr.add(userPictureOpt + jsonuser.getString("userpic_url"));

                    Main.progressBar_process(75 + (15 * i / jsonArray.length()));
                }
            }

            //            Log.i("Main", "urlStr   " +urlStr);
            //            Log.i("Main", "url_feature   " +url_feature);
            //            Log.i("Main", "categoryArr   " +Var.categoryArr);
            //            Log.i("Main", "idArr   " +Var.idArr);
            //            Log.i("Main", "imageLarge_urlArr   " +Var.imageLarge_urlArr);
            //            Log.i("Main", "nameArr   " +Var.nameArr);
            //            Log.i("Main", "ratingArr   " +Var.ratingArr);
            //            Log.i("Main", "user_firstnameArr   " +Var.user_firstnameArr);
            //            Log.i("Main", "user_fullnameArr   " +Var.user_fullnameArr);
            //            Log.i("Main", "user_lastnameArr   " +Var.user_lastnameArr);
            //            Log.i("Main", "user_upgrade_statusArr   " +Var.user_upgrade_statusArr);
            //            Log.i("Main", "user_usernameArr   " +Var.user_usernameArr);
            //            Log.i("Main", "user_userpic_urlArr   " +Var.user_userpic_urlArr);
        } else {
            returnStr = "not response";
            return returnStr;
        }
    } catch (Exception e) {
        e.printStackTrace();
        returnStr = "not response";
        return returnStr;
    }
    return returnStr;
}

From source file:mashberry.com500px.util.Api_Parser.java

/*******************************************************************************
  * //from  ww w.  j  a  va  2  s  .  c  om
  *    (  )
  * 
  *******************************************************************************/
public static String get_second_detail(final int position, final String string, final int url_image_size,
        final int comments, final int comments_page) {
    String returnStr = "success";
    String urlStr = DB.Get_Photo_Url + "/" + string + "?image_size=" + url_image_size
    /*+ "&comments="   + comments
    + "&comments_page="   + comments_page*/
            + "&consumer_key=" + Var.consumer_key;
    try {
        URL url = new URL(urlStr);
        URLConnection uc = url.openConnection();
        HttpURLConnection httpConn = (HttpURLConnection) uc;
        httpConn.setAllowUserInteraction(false);
        httpConn.setInstanceFollowRedirects(true);
        httpConn.setRequestMethod("GET");
        httpConn.connect();
        httpConn.setConnectTimeout(10000);
        int response = httpConn.getResponseCode();

        if (response == HttpURLConnection.HTTP_OK) {
            InputStream in = httpConn.getInputStream();
            String userPictureOpt = "8";
            String result = convertStreamToString(in);
            JSONObject jObject = new JSONObject(result);
            JSONObject jsonObject = jObject.getJSONObject("photo");

            //            Log.i(TAG, "jsonObject " + jsonObject);

            Var.detail_nameMap.put(position, jsonObject.getString("name"));
            Var.detail_locationMap.put(position, jsonObject.getString("location"));
            Var.detail_ratingMap.put(position, jsonObject.getString("rating"));
            Var.detail_times_viewedMap.put(position, jsonObject.getString("times_viewed"));
            Var.detail_votesMap.put(position, jsonObject.getString("votes_count"));
            Var.detail_favoritesMap.put(position, jsonObject.getString("favorites_count"));
            Var.detail_descriptionMap.put(position, jsonObject.getString("description"));
            Var.detail_cameraMap.put(position, jsonObject.getString("camera"));
            Var.detail_lensMap.put(position, jsonObject.getString("lens"));
            Var.detail_focal_lengthMap.put(position, jsonObject.getString("focal_length"));
            Var.detail_isoMap.put(position, jsonObject.getString("iso"));
            Var.detail_shutter_speedMap.put(position, jsonObject.getString("shutter_speed"));
            Var.detail_apertureMap.put(position, jsonObject.getString("aperture"));
            Var.detail_categoryMap.put(position, jsonObject.getString("category"));
            Var.detail_uploadedMap.put(position, jsonObject.getString("hi_res_uploaded"));
            Var.detail_takenMap.put(position, jsonObject.getString("taken_at"));
            Var.detail_licenseTypeMap.put(position, jsonObject.getString("license_type"));

            JSONObject jsonuser = jsonObject.getJSONObject("user");
            Var.detail_user_nameMap.put(position, jsonuser.getString("fullname"));
            Var.detail_userpicMap.put(position, userPictureOpt + jsonuser.getString("userpic_url"));

            //     ( . .)
            /*JSONArray jsonArray = jObject.getJSONArray("comments");
            for(int i=0 ; i<jsonArray.length() ; i++){
               Var.comment_user_id.add(jsonArray.getJSONObject(i).getString("user_id"));
               Var.comment_body.add(jsonArray.getJSONObject(i).getString("body"));
                       
                JSONObject jsonuser = jsonArray.getJSONObject(i).getJSONObject("user");
                Var.comment_fullname.add(jsonuser.getString("fullname"));
                Var.comment_userpic_url.add(jsonuser.getString("userpic_url"));
            }*/

            /*            Log.i("Main", "feature   " +feature);
                        Log.i("Main", "filters   " +filters);
                        Log.i("Main", "categoryArr   " +Var.categoryArr);
                        Log.i("Main", "idArr   " +Var.idArr);
                        Log.i("Main", "image_urlArr   " +Var.image_urlArr);
                        Log.i("Main", "nameArr   " +Var.nameArr);
                        Log.i("Main", "ratingArr   " +Var.ratingArr);
                        Log.i("Main", "user_firstnameArr   " +Var.user_firstnameArr);
                        Log.i("Main", "user_fullnameArr   " +Var.user_fullnameArr);
                        Log.i("Main", "user_lastnameArr   " +Var.user_lastnameArr);
                        Log.i("Main", "user_upgrade_statusArr   " +Var.user_upgrade_statusArr);
                        Log.i("Main", "user_usernameArr   " +Var.user_usernameArr);
                        Log.i("Main", "user_userpic_urlArr   " +Var.user_userpic_urlArr);*/
        } else {
            returnStr = "not response";
            return returnStr;
        }
    } catch (Exception e) {
        e.printStackTrace();
        returnStr = "not response";
        return returnStr;
    }
    return returnStr;
}

From source file:piuk.blockchain.android.ui.RequestCoinsFragment.java

public static String postURL(String request, String urlParameters) throws Exception {

    URL url = new URL(request);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    try {/*ww w .ja  v  a 2  s .co  m*/
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setInstanceFollowRedirects(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("charset", "utf-8");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
        connection.setUseCaches(false);

        connection.setConnectTimeout(30000);
        connection.setReadTimeout(30000);

        connection.connect();

        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        connection.setInstanceFollowRedirects(false);

        if (connection.getResponseCode() != 200)
            throw new Exception(IOUtils.toString(connection.getErrorStream(), "UTF-8"));
        else
            return IOUtils.toString(connection.getInputStream(), "UTF-8");

    } finally {
        connection.disconnect();
    }
}

From source file:org.pixmob.fm2.util.HttpUtils.java

/**
 * Create a new Http connection for an URI.
 *//*  ww  w  .  ja  v  a2 s .  c om*/
public static HttpURLConnection newRequest(Context context, String uri, Set<String> cookies)
        throws IOException {
    if (DEBUG) {
        Log.d(TAG, "Setup connection to " + uri);
    }

    final HttpURLConnection conn = (HttpURLConnection) new URL(uri).openConnection();
    conn.setUseCaches(false);
    conn.setInstanceFollowRedirects(false);
    conn.setConnectTimeout(30000);
    conn.setReadTimeout(60000);
    conn.setRequestProperty("Accept-Encoding", "gzip");
    conn.setRequestProperty("User-Agent", getUserAgent(context));
    conn.setRequestProperty("Cache-Control", "max-age=0");
    conn.setDoInput(true);

    // Close the connection when the request is done, or the application may
    // freeze due to a bug in some Android versions.
    conn.setRequestProperty("Connection", "close");

    if (conn instanceof HttpsURLConnection) {
        setupSecureConnection(context, (HttpsURLConnection) conn);
    }

    if (cookies != null && !cookies.isEmpty()) {
        final StringBuilder buf = new StringBuilder(256);
        for (final String cookie : cookies) {
            if (buf.length() != 0) {
                buf.append("; ");
            }
            buf.append(cookie);
        }
        conn.addRequestProperty("Cookie", buf.toString());
    }

    return conn;
}