Example usage for java.net HttpURLConnection HTTP_FORBIDDEN

List of usage examples for java.net HttpURLConnection HTTP_FORBIDDEN

Introduction

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

Prototype

int HTTP_FORBIDDEN

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

Click Source Link

Document

HTTP Status-Code 403: Forbidden.

Usage

From source file:me.philio.ghost.sync.SyncAdapter.java

/**
 * Access tokens only last 60 minutes so we need to manage this and refresh it frequently. If
 * token has less than 30 minutes remaining it will be refreshed and as a last resort we can
 * use the email/password combination that was saved on login to re-authenticate from scratch.
 *
 * TODO Review later//from w ww.j  a v a  2 s  .  c o m
 */
private void refreshAccessToken(Account account)
        throws AuthenticatorException, OperationCanceledException, IOException, RetrofitError {
    // Check expiry first
    Long expiry = Long
            .parseLong(mAccountManager.getUserData(account, AccountConstants.KEY_ACCESS_TOKEN_EXPIRES));
    if (System.currentTimeMillis() + (30 * 60 * 1000) < expiry) {
        Log.d(TAG, "Access token has more than 30 minutes remaining, won't refresh");
        return;
    }

    // Get blog url and refresh token
    String blogUrl = mAccountManager.getUserData(account, AccountConstants.KEY_BLOG_URL);
    String refreshToken = mAccountManager.blockingGetAuthToken(account, TOKEN_TYPE_REFRESH, false);

    // Get authentication client
    GhostClient client = new GhostClient(blogUrl);
    Authentication authentication = client.createAuthentication();
    try {
        // Request a new access token
        Token token = authentication.blockingGetAccessToken(GRANT_TYPE_REFRESH_TOKEN, CLIENT_ID, refreshToken);

        // Save new access token
        mAccountManager.setAuthToken(account, TOKEN_TYPE_ACCESS, token.accessToken);
        mAccountManager.setUserData(account, KEY_ACCESS_TOKEN_EXPIRES,
                Long.toString(System.currentTimeMillis() + (token.expires * 1000)));
    } catch (RetrofitError e) {
        // Check for a 401/403 as we can try and re-authenticate with an email/password
        if (e.getResponse() != null && (e.getResponse().getStatus() == HttpURLConnection.HTTP_UNAUTHORIZED
                || e.getResponse().getStatus() == HttpURLConnection.HTTP_FORBIDDEN)) {
            String email = mAccountManager.getUserData(account, AccountConstants.KEY_EMAIL);
            String password = mAccountManager.getPassword(account);
            Token token = authentication.blockingGetAccessToken(GRANT_TYPE_PASSWORD, CLIENT_ID, email,
                    password);

            // Save new tokens
            mAccountManager.setAuthToken(account, TOKEN_TYPE_ACCESS, token.accessToken);
            mAccountManager.setAuthToken(account, TOKEN_TYPE_REFRESH, token.refreshToken);
            mAccountManager.setUserData(account, KEY_ACCESS_TOKEN_EXPIRES,
                    Long.toString(System.currentTimeMillis() + (token.expires * 1000)));
        } else {
            // Rethrow the exception if something else went wrong
            throw e;
        }
    }
}

From source file:org.hyperic.hq.plugin.netservices.HTTPCollector.java

private double getAvail(int code) {
    // There are too many options to list everything that is
    // successful. So, instead we are going to call out the
    // things that should be considered failure, everything else
    // is OK.//from   w w  w .j a va  2 s  .com
    switch (code) {
    case HttpURLConnection.HTTP_BAD_REQUEST:
    case HttpURLConnection.HTTP_FORBIDDEN:
    case HttpURLConnection.HTTP_NOT_FOUND:
    case HttpURLConnection.HTTP_BAD_METHOD:
    case HttpURLConnection.HTTP_CLIENT_TIMEOUT:
    case HttpURLConnection.HTTP_CONFLICT:
    case HttpURLConnection.HTTP_PRECON_FAILED:
    case HttpURLConnection.HTTP_ENTITY_TOO_LARGE:
    case HttpURLConnection.HTTP_REQ_TOO_LONG:
    case HttpURLConnection.HTTP_INTERNAL_ERROR:
    case HttpURLConnection.HTTP_NOT_IMPLEMENTED:
    case HttpURLConnection.HTTP_UNAVAILABLE:
    case HttpURLConnection.HTTP_VERSION:
    case HttpURLConnection.HTTP_BAD_GATEWAY:
    case HttpURLConnection.HTTP_GATEWAY_TIMEOUT:
        return Metric.AVAIL_DOWN;
    default:
    }

    if (hasCredentials()) {
        if (code == HttpURLConnection.HTTP_UNAUTHORIZED) {
            return Metric.AVAIL_DOWN;
        }
    }

    return Metric.AVAIL_UP;
}

From source file:com.streamsets.pipeline.stage.origin.httpserver.TestHttpServerPushSource.java

@Test
public void testWithAppIdViaQueryParam() throws Exception {
    RawHttpConfigs httpConfigs = new RawHttpConfigs();
    httpConfigs.appId = () -> "id";
    httpConfigs.port = NetworkUtils.getRandomPort();
    httpConfigs.maxConcurrentRequests = 1;
    httpConfigs.tlsConfigBean.tlsEnabled = false;
    httpConfigs.appIdViaQueryParamAllowed = true;
    HttpServerPushSource source = new HttpServerPushSource(httpConfigs, 1, DataFormat.TEXT,
            new DataParserFormatConfig());
    final PushSourceRunner runner = new PushSourceRunner.Builder(HttpServerDPushSource.class, source)
            .addOutputLane("a").build();
    runner.runInit();/*  w ww  .  jav a 2 s .com*/
    try {
        final List<Record> records = new ArrayList<>();
        runner.runProduce(Collections.<String, String>emptyMap(), 1, new PushSourceRunner.Callback() {
            @Override
            public void processBatch(StageRunner.Output output) {
                records.clear();
                records.addAll(output.getRecords().get("a"));
            }
        });

        // wait for the HTTP server up and running
        HttpReceiverServer httpServer = (HttpReceiverServer) Whitebox.getInternalState(source, "server");
        await().atMost(Duration.TEN_SECONDS).until(isServerRunning(httpServer));

        String url = "http://localhost:" + httpConfigs.getPort() + "?"
                + HttpConstants.SDC_APPLICATION_ID_QUERY_PARAM + "=id";
        Response response = ClientBuilder.newClient().target(url).request().post(Entity.json("Hello"));
        Assert.assertEquals(HttpURLConnection.HTTP_OK, response.getStatus());
        Assert.assertEquals(1, records.size());
        Assert.assertEquals("Hello", records.get(0).get("/text").getValue());

        // Passing wrong App ID in query param should return 403 response
        url = "http://localhost:" + httpConfigs.getPort() + "?" + HttpConstants.SDC_APPLICATION_ID_QUERY_PARAM
                + "=wrongid";
        response = ClientBuilder.newClient().target(url).request().post(Entity.json("Hello"));
        Assert.assertEquals(HttpURLConnection.HTTP_FORBIDDEN, response.getStatus());

        runner.setStop();
    } catch (Exception e) {
        Assert.fail(e.getMessage());
    } finally {
        runner.runDestroy();
    }
}

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 w w.j a  v  a2s.c  o  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:org.okj.im.core.service.QQHttpService.java

/**
 * ?/*from   ww w .  j a v  a 2 s . c  om*/
 * @param conn
 * @return
 */
protected boolean checkResponseCode(final HttpURLConnection conn) {
    boolean success = false;

    //?false;
    if (conn == null) {
        return false;
    }

    try {
        InputStream is = conn.getInputStream();
        if (is == null) {
            return false;
        }

        InputStream isrs = conn.getErrorStream();
        if (isrs != null) {
            return false;
        }

        int status = conn.getResponseCode();
        switch (status) {
        case java.net.HttpURLConnection.HTTP_GATEWAY_TIMEOUT://504
            LogUtils.warn(LOGGER, "! status{0}", status);
            break;
        case java.net.HttpURLConnection.HTTP_FORBIDDEN://403
            LogUtils.warn(LOGGER, "?! status{0}", status);
            break;
        case java.net.HttpURLConnection.HTTP_INTERNAL_ERROR://500
            LogUtils.warn(LOGGER, "WebQQ?! status{0}", status);
            break;
        case java.net.HttpURLConnection.HTTP_NOT_FOUND://404
            LogUtils.warn(LOGGER, "??! status{0}", status);
            break;
        case java.net.HttpURLConnection.HTTP_OK:
            LogUtils.warn(LOGGER, "Connect OK! status{0}", status);
            success = true;
        }
    } catch (IOException ex) {
        LogUtils.error(LOGGER, "??", ex);
    }
    return success;
}

From source file:com.esri.gpt.control.arcims.ServletConnectorProxy.java

/**
 * Communicates with redirect url and works as a transparent proxy
 * /* w w  w .j  a v  a2s.com*/
 * @param request
 *          the servlet request
 * @param response
 *          the servlet response
 * @throws IOException
 *           if an exception occurs
 */
private void executeProxy(HttpServletRequest request, HttpServletResponse response) throws IOException {

    HttpURLConnection httpCon = null;
    URL redirectURL = null;
    InputStream input = null;
    OutputStream output = null;
    InputStream proxyInput = null;
    OutputStream proxyOutput = null;

    try {

        input = request.getInputStream();
        output = response.getOutputStream();

        String sQueryStr = request.getQueryString();
        String sAuthorization = request.getHeader("Authorization");
        String requestBody = readInputCharacters(input);
        String requestMethod = request.getMethod();
        String contentType = request.getContentType();
        String encoding = request.getCharacterEncoding();

        LOGGER.finer(" Request method = " + requestMethod);
        LOGGER.finer(" Query string = " + sQueryStr);
        LOGGER.finer(" Authorization header =" + sAuthorization);
        LOGGER.finer(" Character Encoding = " + encoding);
        LOGGER.finer(" The redirect URL is " + this._redirectURL + "?" + sQueryStr);

        redirectURL = new URL(this._redirectURL + "?" + sQueryStr);

        httpCon = (HttpURLConnection) redirectURL.openConnection();

        httpCon.setDoInput(true);
        httpCon.setDoOutput(true);
        httpCon.setUseCaches(false);
        httpCon.setRequestMethod(requestMethod);
        httpCon.setRequestProperty("Content-type", contentType);

        if (sAuthorization != null) {
            httpCon.addRequestProperty("Authorization", sAuthorization);
        }

        proxyOutput = httpCon.getOutputStream();
        send(requestBody, proxyOutput);

        String authenticateHdr = httpCon.getHeaderField("WWW-Authenticate");
        if (authenticateHdr != null) {
            LOGGER.finer(" WWW-Authenticate : " + authenticateHdr);
            response.setHeader("WWW-Authenticate",
                    StringEscapeUtils.escapeHtml4(Val.stripControls(authenticateHdr)));
        }
        LOGGER.finer(" Response Code : " + httpCon.getResponseCode());

        if ((httpCon.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN)) {

            response.sendError(HttpServletResponse.SC_FORBIDDEN);
        } else if ((httpCon.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED)) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        } else if ((httpCon.getResponseCode() == HttpURLConnection.HTTP_INTERNAL_ERROR)) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } else {
            proxyInput = httpCon.getInputStream();
            send(proxyInput, output);
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (input != null) {
            input.close();
        }
        if (output != null) {
            output.close();
        }
        if (proxyInput != null) {
            proxyInput.close();
        }
        if (proxyOutput != null) {
            proxyOutput.close();
        }
        if (httpCon != null) {
            httpCon.disconnect();
        }
    }
}

From source file:org.apache.geronimo.testsuite.servlets.ServletsTest.java

public void test_ServletSecurityAnnotation() throws Exception {

    Assert.assertEquals(invoke("/SampleServlet5_1", "GET", "alan", "starcraft"), HttpURLConnection.HTTP_OK);
    Assert.assertEquals(invoke("/SampleServlet5_1", "GET", "george", "bone"), HttpURLConnection.HTTP_FORBIDDEN);
    Assert.assertEquals(invoke("/SampleServlet5_1", "POST", "unknown", "unknown"), HttpURLConnection.HTTP_OK);

    Assert.assertEquals(invoke("/SampleServlet5_2", "GET", "unknown", "unknown"), HttpURLConnection.HTTP_OK);
    Assert.assertEquals(invoke("/SampleServlet5_2", "POST", "unknown", "unknown"), HttpURLConnection.HTTP_OK);

    Assert.assertEquals(invoke("/SampleServlet5_3", "GET", "alan", "starcraft"), HttpURLConnection.HTTP_OK);
    Assert.assertEquals(invoke("/SampleServlet5_3", "GET", "george", "bone"), HttpURLConnection.HTTP_FORBIDDEN);
    Assert.assertEquals(invoke("/SampleServlet5_3", "POST", "unknown", "unknown"), HttpURLConnection.HTTP_OK);

    Assert.assertEquals(invoke("/SampleServlet6_1", "POST", "alan", "starcraft"),
            HttpURLConnection.HTTP_FORBIDDEN);
    Assert.assertEquals(invoke("/SampleServlet6_1", "POST", "george", "bone"), HttpURLConnection.HTTP_OK);
    Assert.assertEquals(invoke("/SampleServlet6_1", "GET", "unknown", "unknown"), HttpURLConnection.HTTP_OK);

    Assert.assertEquals(invoke("/TestDynamic", "GET", "gracie", "biscuit"), HttpURLConnection.HTTP_OK);
    Assert.assertEquals(invoke("/TestDynamic", "GET", "alan", "starcraft"), HttpURLConnection.HTTP_FORBIDDEN);

    Assert.assertEquals(invoke("/TestDynamicAfter", "GET", "gracie", "biscuit"), HttpURLConnection.HTTP_OK);
    Assert.assertEquals(invoke("/TestDynamicAfter", "GET", "alan", "starcraft"),
            HttpURLConnection.HTTP_FORBIDDEN);

    Assert.assertEquals(invoke("/SampleServlet3Dynamic", "GET", "gracie", "biscuit"),
            HttpURLConnection.HTTP_FORBIDDEN);

}

From source file:org.lockss.config.HTTPConfigFile.java

private InputStream getUrlInputStream0(String url) throws IOException, MalformedURLException {
    InputStream in = null;/*from w  ww .  j  av  a 2 s .c  o  m*/
    LockssUrlConnection conn = openUrlConnection(url);

    Configuration conf = ConfigManager.getPlatformConfig();
    String proxySpec = conf.get(ConfigManager.PARAM_PROPS_PROXY);
    String proxyHost = null;
    int proxyPort = 0;

    try {
        HostPortParser hpp = new HostPortParser(proxySpec);
        proxyHost = hpp.getHost();
        proxyPort = hpp.getPort();
    } catch (HostPortParser.InvalidSpec e) {
        log.warning("Illegal props proxy: " + proxySpec, e);
    }

    if (proxyHost != null) {
        log.debug2("Setting request proxy to: " + proxyHost + ":" + proxyPort);
        conn.setProxy(proxyHost, proxyPort);
    }
    if (m_config != null && m_lastModified != null) {
        log.debug2("Setting request if-modified-since to: " + m_lastModified);
        conn.setIfModifiedSince(m_lastModified);
    }
    conn.setRequestProperty("Accept-Encoding", "gzip");

    if (m_props != null) {
        Object x = m_props.get(Constants.X_LOCKSS_INFO);
        if (x instanceof String) {
            conn.setRequestProperty(Constants.X_LOCKSS_INFO, (String) x);
        }
    }
    conn.execute();
    if (checkAuth && !conn.isAuthenticatedServer()) {
        IOUtil.safeRelease(conn);
        throw new IOException("Config server not authenticated");
    }

    int resp = conn.getResponseCode();
    String respMsg = conn.getResponseMessage();
    log.debug2(url + " request got response: " + resp + ": " + respMsg);
    switch (resp) {
    case HttpURLConnection.HTTP_OK:
        m_loadError = null;
        m_httpLastModifiedString = conn.getResponseHeaderValue("last-modified");
        log.debug2("New file, or file changed.  Loading file from " + "remote connection:" + url);
        in = conn.getUncompressedResponseInputStream();
        break;
    case HttpURLConnection.HTTP_NOT_MODIFIED:
        m_loadError = null;
        log.debug2("HTTP content not changed, not reloading.");
        IOUtil.safeRelease(conn);
        break;
    case HttpURLConnection.HTTP_NOT_FOUND:
        m_loadError = resp + ": " + respMsg;
        IOUtil.safeRelease(conn);
        throw new FileNotFoundException(m_loadError);
    case HttpURLConnection.HTTP_FORBIDDEN:
        m_loadError = findErrorMessage(resp, conn);
        IOUtil.safeRelease(conn);
        throw new IOException(m_loadError);
    default:
        m_loadError = resp + ": " + respMsg;
        IOUtil.safeRelease(conn);
        throw new IOException(m_loadError);
    }

    return in;
}

From source file:com.streamsets.datacollector.restapi.TestRestApiAuthorization.java

private void test(List<RestApi> apis, boolean authzEnabled) throws Exception {
    String baseUrl = startServer(authzEnabled);
    try {//from   w  w  w  . j  a va2  s  . co m
        for (RestApi api : apis) {
            Set<String> has = api.roles;
            for (String user : ALL_ROLES) {
                user = "guest";
                URL url = new URL(baseUrl + api.uriPath);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestProperty(CsrfProtectionFilter.HEADER_NAME, "CSRF");
                if (authzEnabled) {
                    conn.setRequestProperty("Authorization",
                            "Basic " + Base64.encodeBase64URLSafeString((user + ":" + user).getBytes()));
                }
                conn.setRequestMethod(api.method.name());
                conn.setDefaultUseCaches(false);
                if (authzEnabled) {
                    if (has.contains(user)) {
                        Assert.assertNotEquals(
                                Utils.format("Authz '{}' User '{}' METHOD '{}' API '{}'", authzEnabled, user,
                                        api.method, api.uriPath),
                                HttpURLConnection.HTTP_FORBIDDEN, conn.getResponseCode());
                    } else {
                        Assert.assertEquals(
                                Utils.format("Authz '{}' User '{}' METHOD '{}' API '{}'", authzEnabled, user,
                                        api.method, api.uriPath),
                                HttpURLConnection.HTTP_FORBIDDEN, conn.getResponseCode());
                    }
                } else {
                    Assert.assertNotEquals(
                            Utils.format("Authz '{}' User '{}' METHOD '{}' API '{}'", authzEnabled, user,
                                    api.method, api.uriPath),
                            HttpURLConnection.HTTP_FORBIDDEN, conn.getResponseCode());
                }
            }
        }
    } finally {
        stopServer();
    }
}

From source file:com.box.androidlib.FileTransfer.BoxFileDownload.java

/**
 * Execute a file download.//w  w  w .  j av  a2  s  .  c o  m
 * 
 * @param fileId
 *            The file_id of the file to be downloaded
 * @param destinationFile
 *            A java.io.File resource to which the downloaded file will be written. Ensure that this points to a valid file-path that can be written to.
 * @param versionId
 *            The version_id of the version of the file to download. Set to null to download the latest version of the file.
 * @return a response handler
 * @throws IOException
 *             Can be thrown if there was a connection error, or if destination file could not be written.
 */
public DefaultResponseParser execute(final long fileId, final File destinationFile, final Long versionId)
        throws IOException {

    final DefaultResponseParser handler = new DefaultResponseParser();

    final Uri.Builder builder = new Uri.Builder();
    builder.scheme(BoxConfig.getInstance().getDownloadUrlScheme());
    builder.authority(BoxConfig.getInstance().getDownloadUrlAuthority());
    builder.path(BoxConfig.getInstance().getDownloadUrlPath());
    builder.appendPath(mAuthToken);
    builder.appendPath(String.valueOf(fileId));
    if (versionId != null) {
        builder.appendPath(String.valueOf(versionId));
    }

    // We normally prefer to use HttpUrlConnection, however that appears to fail
    // for certain types of files. For downloads, it appears DefaultHttpClient works
    // more reliably.
    final DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpGet httpGet;
    try {
        httpGet = new HttpGet(new URI(builder.build().toString()));
    } catch (URISyntaxException e) {
        throw new IOException("Invalid Download URL");
    }
    HttpResponse httpResponse = httpclient.execute(httpGet);
    InputStream is = httpResponse.getEntity().getContent();
    int responseCode = httpResponse.getStatusLine().getStatusCode();

    if (responseCode == HttpURLConnection.HTTP_OK) {
        final FileOutputStream fos = new FileOutputStream(destinationFile);
        final byte[] buffer = new byte[DOWNLOAD_BUFFER_SIZE];
        int bufferLength = 0;
        mBytesTransferred = 0;
        long lastOnProgressPost = 0;
        while ((bufferLength = is.read(buffer)) > 0 && !Thread.currentThread().isInterrupted()) {
            fos.write(buffer, 0, bufferLength);
            mBytesTransferred += bufferLength;
            long currTime = SystemClock.uptimeMillis();
            if (mListener != null && mHandler != null
                    && currTime - lastOnProgressPost > ON_PROGRESS_UPDATE_THRESHOLD) {
                lastOnProgressPost = currTime;
                mHandler.post(mOnProgressRunnable);
            }
        }
        mHandler.post(mOnProgressRunnable);
        fos.close();
        handler.setStatus(FileDownloadListener.STATUS_DOWNLOAD_OK);

        // If download thread was interrupted, set to STATUS_DOWNLOAD_CANCELED
        if (Thread.currentThread().isInterrupted()) {
            handler.setStatus(FileDownloadListener.STATUS_DOWNLOAD_CANCELLED);
        }
        // Even if download completed, Box API may have put an error message
        // in the file itself. Refer to
        // http://developers.box.net/w/page/12923951/ApiFunction_Upload-and-Download
        else if (destinationFile.length() < FILE_ERROR_SIZE) {
            final byte[] buff = new byte[(int) destinationFile.length()];
            final FileInputStream fis = new FileInputStream(destinationFile);
            fis.read(buffer);
            final String str = new String(buff).trim();
            if (str.equals(FileDownloadListener.STATUS_DOWNLOAD_WRONG_AUTH_TOKEN)) {
                handler.setStatus(FileDownloadListener.STATUS_DOWNLOAD_WRONG_AUTH_TOKEN);
            } else if (str.equals(FileDownloadListener.STATUS_DOWNLOAD_RESTRICTED)) {
                handler.setStatus(FileDownloadListener.STATUS_DOWNLOAD_RESTRICTED);
            }
        }
    } else if (responseCode == HttpURLConnection.HTTP_FORBIDDEN) {
        handler.setStatus(FileDownloadListener.STATUS_DOWNLOAD_PERMISSIONS_ERROR);
    } else {
        handler.setStatus(FileDownloadListener.STATUS_DOWNLOAD_FAIL);
    }

    is.close();

    return handler;
}