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:org.apache.droids.protocol.http.HttpProtocol.java

@Override
public ManagedContentEntity load(URI uri) throws IOException {
    HttpGet httpget = new HttpGet(uri);
    HttpResponse response = httpclient.execute(httpget);
    StatusLine statusline = response.getStatusLine();
    if (statusline.getStatusCode() >= HttpStatus.SC_BAD_REQUEST) {
        httpget.abort();// ww  w .  j  a  v a2  s  .  c o m
        throw new HttpResponseException(statusline.getStatusCode(), statusline.getReasonPhrase());
    }
    HttpEntity entity = response.getEntity();
    if (entity == null) {
        // Should _almost_ never happen with HTTP GET requests.
        throw new ClientProtocolException("Empty entity");
    }
    long maxlen = httpclient.getParams().getLongParameter(DroidsHttpClient.MAX_BODY_LENGTH, 0);
    return new HttpContentEntity(entity, maxlen);
}

From source file:ch.cyberduck.core.spectra.SpectraExceptionMappingService.java

@Override
public BackgroundException map(final FailedRequestException e) {
    final StringBuilder buffer = new StringBuilder();
    if (null != e.getError()) {
        this.append(buffer, e.getError().getMessage());
    }//w w  w  .j a  v  a  2 s  . c om
    switch (e.getStatusCode()) {
    case HttpStatus.SC_FORBIDDEN:
        if (null != e.getError()) {
            if (StringUtils.isNotBlank(e.getError().getCode())) {
                switch (e.getError().getCode()) {
                case "SignatureDoesNotMatch":
                    return new LoginFailureException(buffer.toString(), e);
                case "InvalidAccessKeyId":
                    return new LoginFailureException(buffer.toString(), e);
                case "InvalidClientTokenId":
                    return new LoginFailureException(buffer.toString(), e);
                case "InvalidSecurity":
                    return new LoginFailureException(buffer.toString(), e);
                case "MissingClientTokenId":
                    return new LoginFailureException(buffer.toString(), e);
                case "MissingAuthenticationToken":
                    return new LoginFailureException(buffer.toString(), e);
                }
            }
        }
    }
    if (e.getCause() instanceof IOException) {
        return new DefaultIOExceptionMappingService().map((IOException) e.getCause());
    }
    return new HttpResponseExceptionMappingService()
            .map(new HttpResponseException(e.getStatusCode(), buffer.toString()));
}

From source file:cn.com.lowe.android.tools.net.response.BinaryHttpResponseHandler.java

@Override
public void sendResponseMessage(HttpResponse response) {
    StatusLine status = response.getStatusLine();
    Header[] contentTypeHeaders = response.getHeaders("Content-Type");
    byte[] responseBody = null;
    if (contentTypeHeaders.length != 1) {
        sendFailureMessage(new HttpResponseException(status.getStatusCode(),
                "None, or more than one, Content-Type Header found!"), responseBody);
        return;//from   www.ja  v  a2  s  .  c om
    }
    Header contentTypeHeader = contentTypeHeaders[0];
    boolean foundAllowedContentType = false;
    for (String anAllowedContentType : mAllowedContentTypes) {
        if (Pattern.matches(anAllowedContentType, contentTypeHeader.getValue())) {
            foundAllowedContentType = true;
        }
    }
    if (!foundAllowedContentType) {
        sendFailureMessage(new HttpResponseException(status.getStatusCode(), "Content-Type not allowed!"),
                responseBody);
        return;
    }
    try {
        HttpEntity entity = null;
        HttpEntity temp = response.getEntity();
        if (temp != null) {
            entity = new BufferedHttpEntity(temp);
        }
        responseBody = EntityUtils.toByteArray(entity);
    } catch (IOException e) {
        sendFailureMessage(e, responseBody);
    }

    if (status.getStatusCode() >= 300) {
        sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()),
                responseBody);
    } else {
        sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody);
    }
}

From source file:com.helger.peppol.smpclient.SMPHttpResponseHandlerWriteOperations.java

@Nullable
public Object handleResponse(@Nonnull final HttpResponse aHttpResponse) throws IOException {
    final StatusLine aStatusLine = aHttpResponse.getStatusLine();
    final HttpEntity aEntity = aHttpResponse.getEntity();
    if (aStatusLine.getStatusCode() >= 300)
        throw new HttpResponseException(aStatusLine.getStatusCode(), aStatusLine.getReasonPhrase());
    if (aEntity == null)
        throw new ClientProtocolException("Response from SMP server contains no content");

    EntityUtils.consume(aEntity);/*from   w  ww .j  a va 2  s  .c  o m*/
    return null;
}

From source file:com.baifendian.swordfish.common.hadoop.YarnRestClient.java

/**
 * ??/*from w w  w  .  ja va 2s . c  o  m*/
 *
 * @param appId
 * @return ? null, ??
 * @throws JSONException
 * @throws IOException
 */
public FlowStatus getApplicationStatus(String appId) throws JSONException, IOException {
    if (StringUtils.isEmpty(appId)) {
        return null;
    }

    String url = ConfigurationUtil.getApplicationStatusAddress(appId);

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpget = new HttpGet(url);

    ResponseHandler<Pair<Integer, String>> rh = response -> {
        StatusLine statusLine = response.getStatusLine();
        HttpEntity entity = response.getEntity();
        if (statusLine.getStatusCode() >= 300) {
            if (statusLine.getStatusCode() == 404 || statusLine.getStatusCode() == 330) {
                return null;
            }

            throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
        }

        if (entity == null) {
            throw new ClientProtocolException("Response contains no content");
        }

        String content = EntityUtils.toString(entity);

        JSONObject o = null;
        try {
            o = new JSONObject(content);
        } catch (JSONException e) {
            throw new HttpResponseException(statusLine.getStatusCode(), content);
        }

        if (!o.has("app") || o.isNull("app")) {
            throw new RuntimeException("Response content not valid " + content);
        }

        try {
            return Pair.of(statusLine.getStatusCode(), o.getJSONObject("app").getString("finalStatus"));
        } catch (JSONException e) {
            throw new HttpResponseException(statusLine.getStatusCode(), content);
        }
    };

    Pair<Integer, String> pair = httpclient.execute(httpget, rh);

    if (pair == null) {
        return null;
    }

    switch (pair.getRight()) {
    case "FAILED":
        return FlowStatus.FAILED;
    case "KILLED":
        return FlowStatus.KILL;
    case "SUCCEEDED":
        return FlowStatus.SUCCESS;
    case "NEW":
    case "NEW_SAVING":
    case "SUBMITTED":
    case "ACCEPTED":
        return FlowStatus.INIT;
    case "RUNNING":
    default:
        return FlowStatus.RUNNING;
    }
}

From source file:com.enjoy.nerd.http.AsyncHttpRequest.java

private void makeRequest() throws IOException {
    if (!Thread.currentThread().isInterrupted()) {
        // Fixes #115
        if (request.getURI().getScheme() == null) {
            // subclass of IOException so processed in the caller
            throw new MalformedURLException("No valid URI scheme was provided");
        }/*from   w w  w  .jav  a  2 s .  co m*/

        HttpResponse response = client.execute(request, context);
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() >= 300) {
            request.abort();
            throw new HttpResponseException(status.getStatusCode(), status.getReasonPhrase());
        }
        if (!Thread.currentThread().isInterrupted()) {
            if (responseHandler != null) {
                responseHandler.sendResponseMessage(response);
            }
        }
    }
}

From source file:me.xiaopan.android.gohttp.JsonHttpResponseHandler.java

@Override
public Object handleResponse(HttpRequest httpRequest, HttpResponse httpResponse) throws Throwable {
    if (!(httpResponse.getStatusLine().getStatusCode() > 100
            && httpResponse.getStatusLine().getStatusCode() < 300)) {
        throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(),
                httpResponse.getStatusLine().getStatusCode() + "" + httpRequest.getUrl());
    }// w  w  w.  ja va 2 s. c  o m

    HttpEntity httpEntity = httpResponse.getEntity();
    if (httpEntity == null) {
        throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(), "HttpEntity is null");
    }

    String jsonString = toString(httpRequest, httpEntity, "UTF-8");

    if (httpRequest.isCanceled()) {
        return null;
    }

    if (jsonString == null || "".equals(jsonString)) {
        throw new Exception("?" + httpRequest.getUrl());
    }

    Gson gson;
    if (excludeFieldsWithoutExposeAnnotation) {
        gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
    } else {
        gson = new Gson();
    }

    if (responseClass != null) { //???
        String readJson;
        String bodyName = parseResponseBodyAnnotation(httpRequest.getGoHttp().getContext(), responseClass);
        if (bodyName != null) {
            readJson = new JSONObject(jsonString).getString(bodyName);
        } else {
            readJson = jsonString;
        }
        return gson.fromJson(readJson, responseClass);
    } else if (responseType != null) { //????
        return gson.fromJson(jsonString, responseType);
    } else {
        throw new Exception("responseClassresponseType?null");
    }
}

From source file:de.incoherent.suseconferenceclient.app.HTTPWrapper.java

public static String getRawText(String url) throws ClientProtocolException, IOException {
    HttpClient client = new DefaultHttpClient();
    HttpGet get = new HttpGet(url);
    Log.d("SUSEConferences", "Get: " + url);
    HttpResponse response = client.execute(get);
    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    if (statusCode >= 200 && statusCode <= 299) {
        StringBuilder builder = new StringBuilder();
        HttpEntity responseEntity = response.getEntity();
        InputStream content = responseEntity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
        String line;/*from   w w w.  ja v a 2s.  co m*/
        while ((line = reader.readLine()) != null) {
            builder.append(line);
        }
        return builder.toString();
    } else {
        throw new HttpResponseException(statusCode, statusLine.getReasonPhrase());
    }

}

From source file:com.esri.geoportal.harvester.waf.WafFile.java

/**
 * Reads content.// w  ww. java  2s.  com
 * @param httpClient HTTP client
 * @param since since date
 * @return content reference
 * @throws IOException if reading content fails
 * @throws URISyntaxException if file url is an invalid URI
 */
public SimpleDataReference readContent(BotsHttpClient httpClient, Date since)
        throws IOException, URISyntaxException {
    HttpGet method = new HttpGet(fileUrl.toExternalForm());
    method.setConfig(DEFAULT_REQUEST_CONFIG);
    HttpClientContext context = creds != null && !creds.isEmpty() ? createHttpClientContext(fileUrl, creds)
            : null;

    try (CloseableHttpResponse httpResponse = httpClient.execute(method, context);
            InputStream input = httpResponse.getEntity().getContent();) {
        if (httpResponse.getStatusLine().getStatusCode() >= 400) {
            throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(),
                    httpResponse.getStatusLine().getReasonPhrase());
        }
        Date lastModifiedDate = readLastModifiedDate(httpResponse);
        MimeType contentType = readContentType(httpResponse);
        boolean readBody = since == null || lastModifiedDate == null
                || lastModifiedDate.getTime() >= since.getTime();
        return new SimpleDataReference(broker.getBrokerUri(), broker.getEntityDefinition().getLabel(),
                fileUrl.toExternalForm(), lastModifiedDate, fileUrl.toURI(),
                readBody ? IOUtils.toByteArray(input) : null, contentType);
    }
}