Example usage for org.apache.http.client HttpResponseException HttpResponseException

List of usage examples for org.apache.http.client HttpResponseException HttpResponseException

Introduction

In this page you can find the example usage for org.apache.http.client HttpResponseException HttpResponseException.

Prototype

public HttpResponseException(final int statusCode, final String s) 

Source Link

Usage

From source file:pl.softech.gw.download.ResourceDownloader.java

public void download(String url, File dir, String fileName) throws IOException {

    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(url);

    HttpResponse response = httpclient.execute(httpGet);

    HttpEntity entity = null;//from w w w .  j  a  v  a2  s . co  m

    BufferedInputStream in = null;
    InputStream ins = null;
    BufferedOutputStream out = null;
    try {
        StatusLine statusLine = response.getStatusLine();
        entity = response.getEntity();

        if (statusLine.getStatusCode() >= 300) {
            EntityUtils.consume(entity);
            throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
        }

        ins = entity.getContent();
        long all = entity.getContentLength();
        in = new BufferedInputStream(ins);
        out = new BufferedOutputStream(new FileOutputStream(new File(dir, fileName)));

        byte[] buffer = new byte[1024];
        int cnt;
        while ((cnt = in.read(buffer)) >= 0) {
            out.write(buffer, 0, cnt);
            fireEvent(new BytesReceivedEvent(cnt, all, fileName));
        }

    } catch (IOException e) {
        fireEvent(new DownloadErrorEvent(String.format("Error during downloading file %s", fileName), e));
        throw e;
    } finally {

        if (ins != null) {
            ins.close();
        }

        if (in != null) {
            in.close();
        }

        if (out != null) {
            out.close();
        }

        httpGet.releaseConnection();
        httpclient.getConnectionManager().shutdown();

    }

}

From source file:com.example.pierre.applicompanies.library_http.RangeFileAsyncHttpResponseHandler.java

@Override
public void sendResponseMessage(HttpResponse response) throws IOException {
    if (!Thread.currentThread().isInterrupted()) {
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() == HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE) {
            //already finished
            if (!Thread.currentThread().isInterrupted())
                sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), null);
        } else if (status.getStatusCode() >= 300) {
            if (!Thread.currentThread().isInterrupted())
                sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null,
                        new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()));
        } else {/*from ww  w.  j  av a2 s.c o m*/
            if (!Thread.currentThread().isInterrupted()) {
                Header header = response.getFirstHeader(AsyncHttpClient.HEADER_CONTENT_RANGE);
                if (header == null) {
                    append = false;
                    current = 0;
                } else {
                    Log.v(LOG_TAG, AsyncHttpClient.HEADER_CONTENT_RANGE + ": " + header.getValue());
                }
                sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(),
                        getResponseData(response.getEntity()));
            }
        }
    }
}

From source file:com.amytech.android.library.utils.asynchttp.RangeFileAsyncHttpResponseHandler.java

@Override
public void sendResponseMessage(HttpResponse response) throws IOException {
    if (!Thread.currentThread().isInterrupted()) {
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() == HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE) {
            // already finished
            if (!Thread.currentThread().isInterrupted())
                sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), null);
        } else if (status.getStatusCode() >= 300) {
            if (!Thread.currentThread().isInterrupted())
                sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null,
                        new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()));
        } else {//from   w  w  w. ja va 2s.  c  om
            if (!Thread.currentThread().isInterrupted()) {
                Header header = response.getFirstHeader(AsyncHttpClient.HEADER_CONTENT_RANGE);
                if (header == null) {
                    append = false;
                    current = 0;
                } else {
                    Log.v(LOG_TAG, AsyncHttpClient.HEADER_CONTENT_RANGE + ": " + header.getValue());
                }
                sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(),
                        getResponseData(response.getEntity()));
            }
        }
    }
}

From source file:com.frand.easyandroid.http.FFStringRespHandler.java

/**
 * ?????//from  w  w  w  .  ja  v a 2s .  co  m
 * ??SUCCESS_MESSAGEkey??handler?
 * ??FAILURE_MESSAGEkey??handler?
 * @param response 
 * @param reqTag 
 * @param reqUrl 
 */
protected void sendRespMsg(HttpResponse response, int reqTag, String reqUrl) {
    StatusLine status = response.getStatusLine();
    String responseBody = null;
    try {
        HttpEntity entity = null;
        HttpEntity temp = response.getEntity();
        if (temp != null) {
            entity = new BufferedHttpEntity(temp);
            responseBody = EntityUtils.toString(entity, "UTF-8");
        }
    } catch (IOException e) {
        sendFailureMsg(e, reqTag, reqUrl);
    }
    if (status.getStatusCode() >= 300) {
        sendFailureMsg(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()), reqTag,
                reqUrl);
    } else {
        sendSuccMsg(responseBody, reqTag, reqUrl);
    }
}

From source file:tv.icntv.common.HttpClientUtil.java

/**
 * Get content by url as string/* w  w w  .ja v a  2 s .c o m*/
 *
 * @param url original url
 * @return page content
 * @throws java.io.IOException
 */
public static String getContent(String url) throws IOException {
    // construct request
    HttpGet request = new HttpGet(url);
    request.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"));

    request.setConfig(RequestConfig.custom().setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT)
            .setSocketTimeout(SOCKET_TIMEOUT).build());
    // construct response handler
    ResponseHandler<String> handler = new ResponseHandler<String>() {
        @Override
        public String handleResponse(final HttpResponse response) throws IOException {
            StatusLine status = response.getStatusLine();
            // status
            if (status.getStatusCode() != HttpStatus.SC_OK) {
                throw new HttpResponseException(status.getStatusCode(), status.getReasonPhrase());
            }
            // get encoding in header
            String encoding = getPageEncoding(response);
            boolean encodingFounded = true;
            if (Strings.isNullOrEmpty(encoding)) {
                encodingFounded = false;
                encoding = "iso-8859-1";
            }
            // get content and find real encoding
            HttpEntity entity = response.getEntity();
            if (entity == null) {
                return null;
            }
            // get content
            byte[] contentBytes = EntityUtils.toByteArray(entity);
            if (contentBytes == null) {
                return null;
            }
            // found encoding
            if (encodingFounded) {
                return new String(contentBytes, encoding);
            }
            // attempt to discover encoding
            String rawContent = new String(contentBytes, DEFAULT_ENCODING);
            Matcher matcher = PATTERN_HTML_CHARSET.matcher(rawContent);
            if (matcher.find()) {
                String realEncoding = matcher.group(1);
                if (!encoding.equalsIgnoreCase(realEncoding)) {
                    // bad luck :(
                    return new String(rawContent.getBytes(encoding), realEncoding);
                }
            }
            // not found right encoding :)
            return rawContent;
        }
    };
    // execute
    CloseableHttpClient client = HttpClientHolder.getClient();
    return client.execute(request, handler);
}

From source file:eu.esdihumboldt.hale.io.codelist.InspireCodeListAdvisor.java

@Override
public void copyResource(LocatableInputSupplier<? extends InputStream> resource, final Path target,
        IContentType resourceType, boolean includeRemote, IOReporter reporter) throws IOException {

    URI uri = resource.getLocation();
    String uriScheme = uri.getScheme();
    if (uriScheme.equals("http")) {
        // Get the response for the given uri
        Response response = INSPIRECodeListReader.getResponse(uri);

        // Handle the fluent response
        response.handleResponse(new ResponseHandler<Boolean>() {

            @Override//from  w ww .  java2 s  .c o  m
            public Boolean handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                StatusLine status = response.getStatusLine();
                HttpEntity entity = response.getEntity();

                if (status.getStatusCode() >= 300) {
                    throw new HttpResponseException(status.getStatusCode(), status.getReasonPhrase());
                }
                if (entity == null) {
                    throw new ClientProtocolException();
                }
                // Copy the resource file to the target path
                Files.copy(entity.getContent(), target);
                return true;
            }
        });
    } else {
        super.copyResource(resource, target, resourceType, includeRemote, reporter);
    }
}

From source file:com.klarna.checkout.Handler.java

/**
 * Verify Status Code./*from   w w w . j  ava 2s .co  m*/
 *
 * @param result HTTP Response object
 *
 * @throws HttpResponseException if code is between 400 and 599 (inclusive)
 * @throws IOException if response could not be read
 */
protected void verifyStatusCode(final HttpResponse result) throws HttpResponseException, IOException {
    if (result.getStatusLine().getStatusCode() >= 400 && result.getStatusLine().getStatusCode() <= 599) {
        throw new HttpResponseException(result.getStatusLine().getStatusCode(),
                EntityUtils.toString(result.getEntity()));
    }
}

From source file:ch.cyberduck.core.b2.B2ErrorResponseInterceptor.java

@Override
public boolean retryRequest(final HttpResponse response, final int executionCount, final HttpContext context) {
    switch (response.getStatusLine().getStatusCode()) {
    case HttpStatus.SC_UNAUTHORIZED:
        if (executionCount <= MAX_RETRIES) {
            final B2ApiException failure;
            try {
                EntityUtils.updateEntity(response, new BufferedHttpEntity(response.getEntity()));
                failure = new B2ApiException(EntityUtils.toString(response.getEntity()),
                        new HttpResponseException(response.getStatusLine().getStatusCode(),
                                response.getStatusLine().getReasonPhrase()));
                if (new B2ExceptionMappingService().map(failure) instanceof ExpiredTokenException) {
                    //  The authorization token is valid for at most 24 hours.
                    try {
                        authorizationToken = session.getClient().authenticate(accountId, applicationKey)
                                .getAuthorizationToken();
                        return true;
                    } catch (B2ApiException | IOException e) {
                        log.warn(String.format("Attempt to renew expired auth token failed. %s",
                                e.getMessage()));
                        return false;
                    }// w w w . ja v  a 2s  .  co m
                }
            } catch (IOException e) {
                log.warn(String.format("Failure parsing response entity from %s", response));
                return false;
            }
        }
    }
    return false;
}

From source file:ch.cyberduck.core.googledrive.DriveBatchDeleteFeature.java

@Override
public void delete(final List<Path> files, final LoginCallback prompt, final Callback callback)
        throws BackgroundException {
    final BatchRequest batch = session.getClient().batch();
    final List<BackgroundException> failures = new ArrayList<>();
    for (Path file : files) {
        try {/*from w  ww  .ja va 2  s.com*/
            session.getClient().files().delete(new DriveFileidProvider(session).getFileid(file)).queue(batch,
                    new JsonBatchCallback<Void>() {
                        @Override
                        public void onFailure(final GoogleJsonError e, final HttpHeaders responseHeaders)
                                throws IOException {
                            log.warn(String.format("Failure deleting %s. %s", file, e.getMessage()));
                            failures.add(new HttpResponseExceptionMappingService()
                                    .map(new HttpResponseException(e.getCode(), e.getMessage())));
                        }

                        @Override
                        public void onSuccess(final Void aVoid, final HttpHeaders responseHeaders)
                                throws IOException {
                            callback.delete(file);
                        }
                    });
        } catch (IOException e) {
            throw new DriveExceptionMappingService().map("Cannot delete {0}", e, file);
        }
    }
    try {
        batch.execute();
    } catch (IOException e) {
        throw new DriveExceptionMappingService().map(e);
    }
    for (BackgroundException e : failures) {
        throw e;
    }
}