Example usage for java.net HttpURLConnection HTTP_MOVED_TEMP

List of usage examples for java.net HttpURLConnection HTTP_MOVED_TEMP

Introduction

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

Prototype

int HTTP_MOVED_TEMP

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

Click Source Link

Document

HTTP Status-Code 302: Temporary Redirect.

Usage

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 w w  w  .  j av 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:org.jboss.test.web.test.SSOBaseCase.java

public static void executeFormLogin(HttpClient httpConn, String warURL) throws IOException, HttpException {
    PostMethod formPost = new PostMethod(warURL + "j_security_check");
    formPost.addRequestHeader("Referer", warURL + "login.html");
    formPost.addParameter("j_username", "jduke");
    formPost.addParameter("j_password", "theduke");
    int responseCode = httpConn.executeMethod(formPost.getHostConfiguration(), formPost, httpConn.getState());
    assertTrue("Saw HTTP_MOVED_TEMP(" + responseCode + ")", responseCode == HttpURLConnection.HTTP_MOVED_TEMP);

    //  Follow the redirect to the index.html page
    Header location = formPost.getResponseHeader("Location");
    String indexURI = location.getValue();
    GetMethod warIndex = new GetMethod(indexURI);
    responseCode = httpConn.executeMethod(warIndex.getHostConfiguration(), warIndex, httpConn.getState());
    assertTrue("Get OK", responseCode == HttpURLConnection.HTTP_OK);
    String body = warIndex.getResponseBodyAsString();
    if (body.indexOf("j_security_check") > 0)
        fail("get of " + indexURI + " redirected to login page");
}

From source file:com.aitangba.volley.BasicNetwork.java

@Override
public NetworkResponse performRequest(Request<?> request) throws VolleyError {
    long requestStart = SystemClock.elapsedRealtime();
    while (true) {
        HttpResponse httpResponse = null;
        byte[] responseContents = null;
        Map<String, String> responseHeaders = Collections.emptyMap();
        try {/*  w ww  . j  a v a2 s .co m*/
            // Gather headers.
            Map<String, String> headers = new HashMap<String, String>();
            addCacheHeaders(headers, request.getCacheEntry());
            httpResponse = mHttpStack.performRequest(request, headers);
            int statusCode = httpResponse.getStatusCode();

            responseHeaders = convertHeaders(httpResponse.getAllHeaders());
            // Handle cache validation.
            if (statusCode == HttpURLConnection.HTTP_NOT_MODIFIED) {

                Cache.Entry entry = request.getCacheEntry();
                if (entry == null) {
                    return new NetworkResponse(HttpURLConnection.HTTP_NOT_MODIFIED, null, responseHeaders, true,
                            SystemClock.elapsedRealtime() - requestStart);
                }

                // A HTTP 304 response does not have all header fields. We
                // have to use the header fields from the cache entry plus
                // the new ones from the response.
                // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5
                entry.responseHeaders.putAll(responseHeaders);
                return new NetworkResponse(HttpURLConnection.HTTP_NOT_MODIFIED, entry.data,
                        entry.responseHeaders, true, SystemClock.elapsedRealtime() - requestStart);
            }

            // Handle moved resources
            if (statusCode == HttpURLConnection.HTTP_MOVED_PERM
                    || statusCode == HttpURLConnection.HTTP_MOVED_TEMP) {
                String newUrl = responseHeaders.get("Location");
                request.setRedirectUrl(newUrl);
            }

            // Some responses such as 204s do not have content.  We must check.
            if (httpResponse.getEntity() != null) {
                responseContents = entityToBytes(httpResponse.getEntity());
            } else {
                // Add 0 byte response as a way of honestly representing a
                // no-content request.
                responseContents = new byte[0];
            }

            // if the request is slow, log it.
            long requestLifetime = SystemClock.elapsedRealtime() - requestStart;
            logSlowRequests(requestLifetime, request, responseContents, httpResponse.getStatusCode());

            if (statusCode < 200 || statusCode > 299) {
                throw new IOException();
            }
            return new NetworkResponse(statusCode, responseContents, responseHeaders, false,
                    SystemClock.elapsedRealtime() - requestStart);
        } catch (SocketTimeoutException e) {
            attemptRetryOnException("socket", request, new TimeoutError());
        } catch (ConnectTimeoutException e) {
            attemptRetryOnException("connection", request, new TimeoutError());
        } catch (MalformedURLException e) {
            throw new RuntimeException("Bad URL " + request.getUrl(), e);
        } catch (IOException e) {
            int statusCode = 0;
            NetworkResponse networkResponse = null;
            if (httpResponse != null) {
                statusCode = httpResponse.getStatusCode();
            } else {
                throw new NoConnectionError(e);
            }
            if (statusCode == HttpURLConnection.HTTP_MOVED_PERM
                    || statusCode == HttpURLConnection.HTTP_MOVED_TEMP) {
                VolleyLog.e("Request at %s has been redirected to %s", request.getOriginUrl(),
                        request.getUrl());
            } else {
                VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl());
            }
            if (responseContents != null) {
                networkResponse = new NetworkResponse(statusCode, responseContents, responseHeaders, false,
                        SystemClock.elapsedRealtime() - requestStart);
                if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED
                        || statusCode == HttpURLConnection.HTTP_FORBIDDEN) {
                    attemptRetryOnException("auth", request, new AuthFailureError(networkResponse));
                } else if (statusCode == HttpURLConnection.HTTP_MOVED_PERM
                        || statusCode == HttpURLConnection.HTTP_MOVED_TEMP) {
                    attemptRetryOnException("redirect", request, new RedirectError(networkResponse));
                } else {
                    // TODO: Only throw ServerError for 5xx status codes.
                    throw new ServerError(networkResponse);
                }
            } else {
                throw new NetworkError(e);
            }
        }
    }
}

From source file:guru.benson.pinch.Pinch.java

/**
 * Read the content length for the ZIP file.
 *
 * @return The content length in bytes or -1 failed.
 *//*from   w  ww  .j a  v a  2 s .  com*/
private int getHttpFileSize() {
    HttpURLConnection conn = null;
    int length = -1;
    try {
        conn = openConnection();
        conn.setRequestMethod(HttpHead.METHOD_NAME);
        conn.connect();

        // handle re-directs
        if (conn.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP) {
            if (setUrl(conn.getHeaderField("Location"))) {
                disconnect(conn);
                length = getHttpFileSize();
            }
        } else {
            length = conn.getContentLength();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        disconnect(conn);
    }

    log("Content length is " + length + " bytes");

    return length;
}

From source file:mobi.jenkinsci.ci.client.sso.GoogleSsoHandler.java

@Override
public String doTwoStepAuthentication(final HttpClient httpClient, final HttpContext httpContext,
        final HttpResponse response, final String otp) throws IOException {
    final HttpPost formPost = getOtpFormPost(httpContext, response, otp);
    Element otpResponseForm;//from   ww w .j  a v a  2  s  . c  o  m
    try {
        final HttpResponse otpResponse = httpClient.execute(formPost, httpContext);
        if (otpResponse.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_OK) {
            throw getException(otpResponse);
        }

        final Document otpResponseDoc = Jsoup.parse(otpResponse.getEntity().getContent(), "UTF-8", "");
        otpResponseForm = otpResponseDoc.select("form[id=hiddenpost]").first();
        if (otpResponseForm == null) {
            final Element errorDiv = otpResponseDoc.select("div[id=error]").first();
            if (errorDiv == null) {
                throw new IOException(
                        "2nd-step authentication FAILED: Google did not return positive response form.");
            } else {
                throw new TwoPhaseAuthenticationRequiredException(getDivText(errorDiv),
                        GOOGLE_ANDROID_APPS_AUTHENTICATOR2_APP_ID);
            }
        }
    } finally {
        formPost.releaseConnection();
    }

    final HttpPost formCompletePost = JenkinsFormAuthHttpClient
            .getPostForm(JenkinsFormAuthHttpClient.getLatestRedirectedUrl(httpContext), otpResponseForm, null);
    try {
        final HttpResponse otpCompleteResponse = httpClient.execute(formCompletePost, httpContext);
        if (otpCompleteResponse.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_MOVED_TEMP) {
            throw new IOException(
                    String.format("2nd-step authentication failed: Google returned HTTP-Status:%d %s",
                            otpCompleteResponse.getStatusLine().getStatusCode(),
                            otpCompleteResponse.getStatusLine().getReasonPhrase()));
        }

        return otpCompleteResponse.getFirstHeader("Location").getValue();
    } finally {
        formCompletePost.releaseConnection();
    }
}

From source file:eu.semlibproject.annotationserver.restapis.ServicesAPI.java

/**
 * Implement a simple proxy//  w  w w  .j a  v  a2s  .co m
 *
 * @param requestedURL the requested URL
 * @param req the HttpServletRequest
 * @return
 */
@GET
@Path("proxy")
public Response proxy(@QueryParam(SemlibConstants.URL_PARAM) String requestedURL,
        @Context HttpServletRequest req) {

    BufferedReader in = null;

    try {
        URL url = new URL(requestedURL);
        URLConnection urlConnection = url.openConnection();

        int proxyConnectionTimeout = ConfigManager.getInstance().getProxyAPITimeout();

        // Set base properties
        urlConnection.setUseCaches(false);
        urlConnection.setConnectTimeout(proxyConnectionTimeout * 1000); // set max response timeout 15 sec

        String acceptedDataFormat = req.getHeader(SemlibConstants.HTTP_HEADER_ACCEPT);
        if (StringUtils.isNotBlank(acceptedDataFormat)) {
            urlConnection.addRequestProperty(SemlibConstants.HTTP_HEADER_ACCEPT, acceptedDataFormat);
        }

        // Open the connection
        urlConnection.connect();

        if (urlConnection instanceof HttpURLConnection) {
            HttpURLConnection httpConnection = (HttpURLConnection) urlConnection;

            int statusCode = httpConnection.getResponseCode();
            if (statusCode == HttpURLConnection.HTTP_MOVED_TEMP
                    || statusCode == HttpURLConnection.HTTP_MOVED_PERM) {
                // Follow the redirect
                String newLocation = httpConnection.getHeaderField(SemlibConstants.HTTP_HEADER_LOCATION);
                httpConnection.disconnect();

                if (StringUtils.isNotBlank(newLocation)) {
                    return this.proxy(newLocation, req);
                } else {
                    return Response.status(statusCode).build();
                }
            } else if (statusCode == HttpURLConnection.HTTP_OK) {

                // Send the response
                StringBuilder sbf = new StringBuilder();

                // Check if the contentType is supported
                boolean contentTypeSupported = false;
                String contentType = httpConnection.getHeaderField(SemlibConstants.HTTP_HEADER_CONTENT_TYPE);
                List<String> supportedMimeTypes = ConfigManager.getInstance().getProxySupportedMimeTypes();
                if (contentType != null) {
                    for (String cMime : supportedMimeTypes) {
                        if (contentType.equals(cMime) || contentType.contains(cMime)) {
                            contentTypeSupported = true;
                            break;
                        }
                    }
                }

                if (!contentTypeSupported) {
                    httpConnection.disconnect();
                    return Response.status(Status.NOT_ACCEPTABLE).build();
                }

                String contentEncoding = httpConnection.getContentEncoding();
                if (StringUtils.isBlank(contentEncoding)) {
                    contentEncoding = "UTF-8";
                }

                InputStreamReader inStrem = new InputStreamReader((InputStream) httpConnection.getContent(),
                        Charset.forName(contentEncoding));
                in = new BufferedReader(inStrem);

                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    sbf.append(inputLine);
                    sbf.append("\r\n");
                }

                in.close();
                httpConnection.disconnect();

                return Response.status(statusCode).header(SemlibConstants.HTTP_HEADER_CONTENT_TYPE, contentType)
                        .entity(sbf.toString()).build();

            } else {
                httpConnection.disconnect();
                return Response.status(statusCode).build();
            }
        }

        return Response.status(Status.BAD_REQUEST).build();

    } catch (MalformedURLException ex) {
        logger.log(Level.SEVERE, null, ex);
        return Response.status(Status.BAD_REQUEST).build();
    } catch (IOException ex) {
        logger.log(Level.SEVERE, null, ex);
        return Response.status(Status.INTERNAL_SERVER_ERROR).build();
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException ex) {
                logger.log(Level.SEVERE, null, ex);
                return Response.status(Status.INTERNAL_SERVER_ERROR).build();
            }
        }
    }
}

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 ww w. j  ava2s.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;
    }/* w  w  w .  j  ava  2 s. c  om*/

    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:io.github.hidroh.materialistic.accounts.UserServicesClient.java

@Override
public void reply(Context context, String parentId, String text, Callback callback) {
    Pair<String, String> credentials = AppUtils.getCredentials(context);
    if (credentials == null) {
        callback.onDone(false);//from   w w w. j a  v  a  2  s. co  m
        return;
    }
    execute(postReply(parentId, text, credentials.first, credentials.second))
            .map(response -> response.code() == HttpURLConnection.HTTP_MOVED_TEMP)
            .observeOn(AndroidSchedulers.mainThread()).subscribe(callback::onDone, callback::onError);
}

From source file:httpget.HttpGet.java

private void obtainConnection() throws HttpGetException {
    try {//from   w  w  w  .  ja va  2s  . com
        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));
    }
}