Example usage for java.net HttpURLConnection HTTP_SEE_OTHER

List of usage examples for java.net HttpURLConnection HTTP_SEE_OTHER

Introduction

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

Prototype

int HTTP_SEE_OTHER

To view the source code for java.net HttpURLConnection HTTP_SEE_OTHER.

Click Source Link

Document

HTTP Status-Code 303: See Other.

Usage

From source file:com.alexoree.jenkins.Main.java

private static String download(String localName, String remoteUrl) throws Exception {
    URL obj = new URL(remoteUrl);
    HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
    conn.setReadTimeout(5000);//from w  w  w.ja  v  a2 s. c  o m

    System.out.println("Request URL ... " + remoteUrl);

    boolean redirect = false;

    // normally, 3xx is redirect
    int status = conn.getResponseCode();
    if (status != HttpURLConnection.HTTP_OK) {
        if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                || status == HttpURLConnection.HTTP_SEE_OTHER)
            redirect = true;
    }

    if (redirect) {

        // get redirect url from "location" header field
        String newUrl = conn.getHeaderField("Location");

        // get the cookie if need, for login
        String cookies = conn.getHeaderField("Set-Cookie");

        // open the new connnection again
        conn = (HttpURLConnection) new URL(newUrl).openConnection();

        String version = newUrl.substring(newUrl.lastIndexOf("/", newUrl.lastIndexOf("/") - 1) + 1,
                newUrl.lastIndexOf("/"));
        String pluginname = localName.substring(localName.lastIndexOf("/") + 1);
        String ext = "";
        if (pluginname.endsWith(".war"))
            ext = ".war";
        else
            ext = ".hpi";

        pluginname = pluginname.replace(ext, "");
        localName = localName.replace(pluginname + ext,
                "/download/plugins/" + pluginname + "/" + version + "/");
        new File(localName).mkdirs();
        localName += pluginname + ext;
        System.out.println("Redirect to URL : " + newUrl);

    }
    if (new File(localName).exists()) {
        System.out.println(localName + " exists, skipping");
        return localName;
    }

    byte[] buffer = new byte[2048];

    FileOutputStream baos = new FileOutputStream(localName);
    InputStream inputStream = conn.getInputStream();
    int totalBytes = 0;
    int read = inputStream.read(buffer);
    while (read > 0) {
        totalBytes += read;
        baos.write(buffer, 0, read);
        read = inputStream.read(buffer);
    }
    System.out.println("Retrieved " + totalBytes + "bytes");

    return localName;

}

From source file:com.none.tom.simplerssreader.net.FeedDownloader.java

@SuppressWarnings("ConstantConditions")
public static InputStream getInputStream(final Context context, final String feedUrl) {
    final ConnectivityManager manager = context.getSystemService(ConnectivityManager.class);
    final NetworkInfo info = manager.getActiveNetworkInfo();

    if (info == null || !info.isConnected()) {
        ErrorHandler.setErrno(ErrorHandler.ERROR_NETWORK);
        LogUtils.logError("No network connection");
        return null;
    }/*from ww  w.  ja v a2  s.c o  m*/

    URL url;
    try {
        url = new URL(feedUrl);
    } catch (final MalformedURLException e) {
        ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_BAD_REQUEST, e);
        return null;
    }

    final boolean[] networkPrefs = DefaultSharedPrefUtils.getNetworkPreferences(context);
    final boolean useHttpTorProxy = networkPrefs[0];
    final boolean httpsOnly = networkPrefs[1];
    final boolean followRedir = networkPrefs[2];

    for (int nrRedirects = 0;; nrRedirects++) {
        if (nrRedirects >= HTTP_NR_REDIRECTS_MAX) {
            ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_TOO_MANY_REDIRECTS);
            LogUtils.logError("Too many redirects");
            return null;
        }

        HttpURLConnection conn = null;

        try {
            if (httpsOnly && url.getProtocol().equalsIgnoreCase("http")) {
                ErrorHandler.setErrno(ErrorHandler.ERROR_HTTPS_ONLY);
                LogUtils.logError("Attempting insecure connection");
                return null;
            }

            if (useHttpTorProxy) {
                conn = (HttpURLConnection) url.openConnection(new Proxy(Proxy.Type.HTTP,
                        new InetSocketAddress(InetAddress.getByName(HTTP_PROXY_TOR_IP), HTTP_PROXY_TOR_PORT)));
            } else {
                conn = (HttpURLConnection) url.openConnection();
            }

            conn.setRequestProperty("Accept-Charset", StandardCharsets.UTF_8.name());

            conn.setConnectTimeout(HTTP_URL_DEFAULT_TIMEOUT);
            conn.setReadTimeout(HTTP_URL_DEFAULT_TIMEOUT);

            conn.connect();

            final int responseCode = conn.getResponseCode();

            switch (responseCode) {
            case HttpURLConnection.HTTP_OK:
                return getInputStream(conn.getInputStream());
            case HttpURLConnection.HTTP_MOVED_PERM:
            case HttpURLConnection.HTTP_MOVED_TEMP:
            case HttpURLConnection.HTTP_SEE_OTHER:
            case HTTP_TEMP_REDIRECT:
                if (followRedir) {
                    final String location = conn.getHeaderField("Location");
                    url = new URL(url, location);

                    if (responseCode == HttpURLConnection.HTTP_MOVED_PERM) {
                        SharedPrefUtils.updateSubscriptionUrl(context, url.toString());
                    }
                    continue;
                }
                ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_FOLLOW_REDIRECT_DENIED);
                LogUtils.logError("Couldn't follow redirect");
                return null;
            default:
                if (responseCode < 0) {
                    ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_RESPONSE);
                    LogUtils.logError("No valid HTTP response");
                    return null;
                } else if (responseCode >= 400 && responseCode <= 500) {
                    ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_CLIENT);
                } else if (responseCode >= 500 && responseCode <= 600) {
                    ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_SERVER);
                } else {
                    ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_UNHANDLED);
                }
                LogUtils.logError("Error " + responseCode + ": " + conn.getResponseMessage());
                return null;
            }
        } catch (final IOException e) {
            if ((e instanceof ConnectException && e.getMessage().equals("Network is unreachable"))
                    || e instanceof SocketTimeoutException || e instanceof UnknownHostException) {
                ErrorHandler.setErrno(ErrorHandler.ERROR_NETWORK, e);
            } else {
                ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_UNHANDLED, e);
            }
            return null;
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
    }
}

From source file:httpget.HttpGet.java

private void obtainConnection() throws HttpGetException {
    try {//from  ww w .  ja  v a2s .  c om
        this.connection = (HttpURLConnection) url.openConnection();
        this.connection.setInstanceFollowRedirects(true);
        this.connection.setReadTimeout(this.maxTimeout * 1000);
        if (this.requestHeaders != null) {
            Iterator i = this.requestHeaders.entrySet().iterator();
            while (i.hasNext()) {
                Map.Entry pair = (Map.Entry) i.next();
                this.connection.setRequestProperty((String) pair.getKey(), (String) pair.getValue());
            }
        }
        this.connection.connect();
        this.responseCode = this.connection.getResponseCode();
        if (this.responseCode == HttpURLConnection.HTTP_SEE_OTHER
                || this.responseCode == HttpURLConnection.HTTP_MOVED_TEMP
                || this.responseCode == HttpURLConnection.HTTP_MOVED_PERM) {
            this.redirected_from[this.nRedirects++] = this.url.toString();
            if (this.connection.getHeaderField("location") != null)
                this.setUrl(this.connection.getHeaderField("location"));
            else
                this.setUrl(this.redirectFromResponse());
            this.obtainConnection();
        }

        if (this.responseCode == HttpURLConnection.HTTP_FORBIDDEN) {
            throw new HttpGetException("Toegang verboden (403)", this.url.toString(),
                    new Exception("Toegang verboden (403)"), redirected_from);
        }
        String mimeParts[] = this.connection.getContentType().split(";");
        this.mimeType = mimeParts[0];
    } catch (SocketTimeoutException e) {
        throw (new HttpGetException("Timeout bij ophalen gegevens", this.url.toString(), e, redirected_from));
    } catch (IOException e) {
        throw (new HttpGetException("Probleem met verbinden", this.url.toString(), e, redirected_from));
    }
}

From source file:com.andrious.btc.data.jsonUtils.java

private static boolean handleResponse(int response, HttpURLConnection conn) {

    if (response == HttpURLConnection.HTTP_OK) {

        return true;
    }//from   w w  w .j a  va 2s . c  o m

    if (response == HttpURLConnection.HTTP_MOVED_TEMP || response == HttpURLConnection.HTTP_MOVED_PERM
            || response == HttpURLConnection.HTTP_SEE_OTHER) {

        String newURL = conn.getHeaderField("Location");

        conn.disconnect();

        try {

            // get redirect url from "location" header field and open a new connection again
            conn = urlConnect(newURL);

            return true;

        } catch (IOException ex) {

            throw new RuntimeException(ex);
        }
    }

    // Nothing to be done. Can't go any further.
    return false;
}

From source file:com.atlassian.launchpad.jira.whiteboard.WhiteboardTabPanel.java

@Override
public List<IssueAction> getActions(Issue issue, User remoteUser) {
    List<IssueAction> messages = new ArrayList<IssueAction>();

    //retrieve and validate url from custom field
    CustomField bpLinkField = ComponentAccessor.getCustomFieldManager()
            .getCustomFieldObjectByName(LAUNCHPAD_URL_FIELD_NAME);

    if (bpLinkField == null) {
        messages.add(new GenericMessageAction("\"" + LAUNCHPAD_URL_FIELD_NAME
                + "\" custom field not available. Cannot process Gerrit Review comments"));
        return messages;
    }//from w  w w  .j a v a2  s .  co m

    Object bpURLFieldObj = issue.getCustomFieldValue(bpLinkField);
    if (bpURLFieldObj == null) {
        messages.add(new GenericMessageAction("\"" + LAUNCHPAD_URL_FIELD_NAME
                + "\" not provided. Please provide the Launchpad URL to view the whiteboard for this issue."));
        return messages;
    }

    String bpURL = bpURLFieldObj.toString().trim();

    if (bpURL.length() == 0) {
        messages.add(
                new GenericMessageAction("To view the Launchpad Blueprint for this issue please provide the "
                        + LAUNCHPAD_URL_FIELD_NAME));
        return messages;
    }

    if (!bpURL.matches(URL_REGEX)) {
        messages.add(new GenericMessageAction(
                "Launchpad URL not properly formatted. Please provide URL that appears as follows:<br/> https://blueprints.launchpad.net/devel/PROJECT NAME/+spec/BLUEPRINT NAME"));
        return messages;
    }

    String apiQuery = bpURL.substring(
            (bpURL.lastIndexOf(BASE_LAUNCHPAD_BLUEPRINT_HOST) + BASE_LAUNCHPAD_BLUEPRINT_HOST.length()));

    String url = BASE_LAUNCHPAD_API_URL + API_VERSION + apiQuery;

    try {
        //establish api connection
        URL obj = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) obj.openConnection();

        boolean redirect = false;

        // normally, 3xx is redirect
        int status = conn.getResponseCode();
        if (status != HttpURLConnection.HTTP_OK) {
            if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                    || status == HttpURLConnection.HTTP_SEE_OTHER)
                redirect = true;
        }

        if (redirect) {
            // get redirect url from "location" header field
            String newUrl = conn.getHeaderField("Location");

            // open the new connection
            conn = (HttpURLConnection) new URL(newUrl).openConnection();
        }

        //parse returned json
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuffer json = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            json.append(inputLine);
        }
        in.close();

        //generate tab content
        JSONTokener tokener = new JSONTokener(json.toString());
        JSONObject finalResult = new JSONObject(tokener);
        if (finalResult.has(WHITEBOARD) && finalResult.getString(WHITEBOARD).length() > 0) {
            messages.add(new GenericMessageAction(
                    escapeHtml(finalResult.getString(WHITEBOARD)).replaceAll("\n", "<br/>")));
        } else {
            messages.add(new GenericMessageAction("No whiteboard for this blueprint."));
        }

    } catch (JSONException e) {
        // whiteboard JSON key not found
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        //unable to find the requested whiteboard
        messages.add(new GenericMessageAction(
                "Unable to find desired blueprint. Please check that the URL references the correct blueprint."));
        return messages;
    } catch (IOException e) {
        // Exception in attempting to read from Launchpad API
        e.printStackTrace();
    }

    return messages;
}

From source file:uk.ac.ucl.excites.sapelli.collector.util.AsyncDownloader.java

private boolean download(String downloadUrl) {
    if (downloadUrl == null || downloadUrl.isEmpty()) {
        failure = new Exception("No URL given!");
        return false;
    }/*from   www.  jav a  2  s.co  m*/

    //Log.d(getClass().getSimpleName(), "Download URL: " + downloadUrl);
    if (DeviceControl.isOnline(context)) {
        InputStream input = null;
        OutputStream output = null;
        try {
            URL url = new URL(downloadUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setInstanceFollowRedirects(false); // we handle redirects manually below (otherwise HTTP->HTTPS redirects don't work):
            conn.connect();

            // Detect & follow redirects:
            int status = conn.getResponseCode();
            //Log.d(getClass().getSimpleName(), "Response Code: " + status);
            if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                    || status == HttpURLConnection.HTTP_SEE_OTHER) { // follow redirect url from "location" header field
                String newUrl = conn.getHeaderField("Location");
                //Log.d(getClass().getSimpleName(), "Redirect to URL : " + newUrl);
                return download(newUrl);
            }

            // Getting file length
            final int fileLength = conn.getContentLength();
            publishProgress(fileLength < 0 ? // when fileLength = -1 this means the server hasn't specified the file length
                    -1 : // progressDialog will open and be set to indeterminate mode
                    0); // progressDialog will open and be set to 0

            // Input stream to read file - with 8k buffer
            input = new BufferedInputStream(url.openStream(), 8192);
            // Output stream to write file
            output = new BufferedOutputStream(new FileOutputStream(downloadedFile));

            byte data[] = new byte[1024];
            int total = 0;
            int percentage = 0;
            int bytesRead;
            while ((bytesRead = input.read(data)) != -1) {
                // Complete % completion:
                if (fileLength > 0) // don't divide by 0 and only update progress if we know the fileLength (i.e. != -1)
                {
                    int newPercentage = (int) ((total += bytesRead) / ((float) fileLength) * 100f);
                    if (newPercentage != percentage)
                        publishProgress(percentage = newPercentage);
                }

                // Write data to file...
                output.write(data, 0, bytesRead);
            }

            // Flush output:
            output.flush();
        } catch (Exception e) {
            failure = e;
            return false;
        } finally { // Close streams:
            StreamHelpers.SilentClose(input);
            StreamHelpers.SilentClose(output);
        }
        //Log.d(getClass().getSimpleName(), "Download done");
        return true;
    } else {
        failure = new Exception("The device is not online.");
        return false;
    }
}

From source file:org.sociotech.communitymashup.source.mendeley.sdkadaption.AdaptedDocumentServiceImpl.java

protected String callGetForRedirectUrl(String apiUrl) {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false);

    try {//from w w w  .j  a v  a 2  s  . c o  m
        HttpGet httpget = new HttpGet(apiUrl);
        if (!requestParameters.isEmpty()) {
            HttpParams params = httpget.getParams();
            for (String name : requestParameters.keySet()) {
                params.setParameter(name, requestParameters.get(name));
            }
        }

        for (String headerName : requestHeaders.keySet()) {
            httpget.addHeader(headerName, requestHeaders.get(headerName));
        }

        signRequest(httpget);

        HttpResponse response = httpclient.execute(httpget);

        if (!((response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_MOVED_TEMP)
                || (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_MOVED_PERM)
                || (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_SEE_OTHER))) {
            return null;
        }

        // redirect location is in location header
        Header[] locationHeader = response.getHeaders("location");

        if (locationHeader.length >= 1) {
            return locationHeader[0].getValue();
        }
    } catch (IOException e) {
        throw new MendeleyException(e);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        // httpclient.getConnectionManager().shutdown();
    }

    return null;
}

From source file:com.github.dozermapper.core.builder.xml.SchemaLSResourceResolver.java

/**
 * Attempts to open a http connection for the systemId resource, and follows the first redirect
 *
 * @param systemId url to the XSD// w  w  w. j  a v  a2 s .  c o m
 * @return stream to XSD
 * @throws IOException if fails to find XSD
 */
private InputStream resolveFromURL(String systemId) throws IOException {
    LOG.debug("Trying to download [{}]", systemId);

    URL obj = new URL(systemId);
    HttpURLConnection conn = (HttpURLConnection) obj.openConnection();

    int status = conn.getResponseCode();
    if ((status != HttpURLConnection.HTTP_OK) && (status == HttpURLConnection.HTTP_MOVED_TEMP
            || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER)) {

        LOG.debug("Received status of {}, attempting to follow Location header", status);

        String newUrl = conn.getHeaderField("Location");
        conn = (HttpURLConnection) new URL(newUrl).openConnection();
    }

    return conn.getInputStream();
}

From source file:net.mceoin.cominghome.api.NestUtil.java

private static String getNestAwayStatusCall(String access_token) {

    String away_status = "";

    String urlString = "https://developer-api.nest.com/structures?auth=" + access_token;
    log.info("url=" + urlString);

    StringBuilder builder = new StringBuilder();
    boolean error = false;
    String errorResult = "";

    HttpURLConnection urlConnection = null;
    try {// ww w  .jav a 2s . c  o  m
        URL url = new URL(urlString);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestProperty("User-Agent", "ComingHomeBackend/1.0");
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.setConnectTimeout(15000);
        urlConnection.setReadTimeout(15000);
        //            urlConnection.setChunkedStreamingMode(0);

        //            urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf8");

        boolean redirect = false;

        // normally, 3xx is redirect
        int status = urlConnection.getResponseCode();
        if (status != HttpURLConnection.HTTP_OK) {
            if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                    || status == 307 // Temporary redirect
                    || status == HttpURLConnection.HTTP_SEE_OTHER)
                redirect = true;
        }

        //            System.out.println("Response Code ... " + status);

        if (redirect) {

            // get redirect url from "location" header field
            String newUrl = urlConnection.getHeaderField("Location");

            // open the new connnection again
            urlConnection = (HttpURLConnection) new URL(newUrl).openConnection();
            urlConnection.setRequestMethod("PUT");
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            //                urlConnection.setChunkedStreamingMode(0);

            //                System.out.println("Redirect to URL : " + newUrl);

        }

        int statusCode = urlConnection.getResponseCode();

        log.info("statusCode=" + statusCode);
        if ((statusCode == HttpURLConnection.HTTP_OK)) {
            error = false;

            InputStream response;
            response = urlConnection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(response));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            log.info("response=" + builder.toString());
            JSONObject object = new JSONObject(builder.toString());

            Iterator keys = object.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                JSONObject structure = object.getJSONObject(key);

                if (structure.has("away")) {
                    away_status = structure.getString("away");
                } else {
                    log.info("missing away");
                }
            }

        } else if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
            // bad auth
            error = true;
            errorResult = "Unauthorized";
        } else if (statusCode == HttpURLConnection.HTTP_BAD_REQUEST) {
            error = true;
            InputStream response;
            response = urlConnection.getErrorStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(response));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            log.info("response=" + builder.toString());
            JSONObject object = new JSONObject(builder.toString());

            Iterator keys = object.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                if (key.equals("error")) {
                    // error = Internal Error on bad structure_id
                    errorResult = object.getString("error");
                    log.info("errorResult=" + errorResult);
                }
            }
        } else {
            error = true;
            errorResult = Integer.toString(statusCode);
        }

    } catch (IOException e) {
        error = true;
        errorResult = e.getLocalizedMessage();
        log.warning("IOException: " + errorResult);
    } catch (Exception e) {
        error = true;
        errorResult = e.getLocalizedMessage();
        log.warning("Exception: " + errorResult);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }

    if (error)
        away_status = "Error: " + errorResult;
    return away_status;
}

From source file:com.elevenpaths.googleindexretriever.GoogleSearch.java

public String responseCaptcha(String responseCaptcha) {
    String url = "https://ipv4.google.com/sorry/CaptchaRedirect";
    String request = url + "?q=" + q + "&hl=es&continue=" + continueCaptcha + "&id=" + idCaptcha + "&captcha="
            + responseCaptcha + "&submit=Enviar";
    String newCookie = "";

    try {//  ww w  .  j a v  a  2  s.  c om
        URL obj = new URL(request);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // optional default is GET
        con.setRequestMethod("GET");

        // add request header
        con.setRequestProperty("Host", "ipv4.google.com");
        con.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0");
        con.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        con.setRequestProperty("Accept-Language", "es-ES,es;q=0.8,en-US;q=0.5,en;q=0.3");
        con.setRequestProperty("Accept-Encoding", "gzip, deflate, br");
        con.setRequestProperty("Cookie", tokenCookie + "; path=/; domain=google.com");
        con.addRequestProperty("Connection", "keep-alive");
        con.setRequestProperty("Referer", referer);
        //con.connect();
        boolean redirect = false;
        con.setInstanceFollowRedirects(false);
        int status = con.getResponseCode();

        if (status != HttpURLConnection.HTTP_OK) {
            if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                    || status == HttpURLConnection.HTTP_SEE_OTHER)
                redirect = true;
        }

        if (redirect) {

            // get redirect url from "location" header field
            String newUrl = con.getHeaderField("Location");

            // open the new connnection again
            con = (HttpURLConnection) new URL(newUrl).openConnection();
            con.setRequestProperty("User-Agent",
                    "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0");
            con.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            con.setRequestProperty("Referer", referer);
            con.setRequestProperty("Accept-Encoding", "gzip, deflate");
            con.setRequestProperty("Cookie", tokenCookie);
            con.addRequestProperty("Connection", "keep-alive");

            // Find the cookie
            String nextURL = URLDecoder.decode(newUrl, "UTF-8");
            String[] k = nextURL.split("&");
            for (String a : k) {
                if (a.startsWith("google_abuse=")) {
                    String temp = a.replace("google_abuse=", "");
                    String[] c = temp.split(";");
                    for (String j : c) {
                        if (j.startsWith("GOOGLE_ABUSE_EXEMPTION")) {
                            newCookie = j;
                        }
                    }

                }
            }
        }

        con.connect();

        if (con.getResponseCode() == 200) {
            newCookie = tokenCookie;
        }
    } catch (IOException e) {
        e.printStackTrace();

    }

    return newCookie;

}