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

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

Introduction

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

Prototype

public ClientProtocolException(final Throwable cause) 

Source Link

Usage

From source file:fr.treeptik.cloudunit.cli.exception.CustomResponseErrorHandler.java

@Override
public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {

    int status = response.getStatusLine().getStatusCode();

    if (status >= 200 && status < 300) {
        HttpEntity entity = response.getEntity();
        return entity != null ? EntityUtils.toString(entity) : null;
    } else {//from  ww w. j  a  va  2 s.  co  m

        switch (status) {
        case 500:
            InputStreamReader reader = null;
            reader = new InputStreamReader(response.getEntity().getContent());
            LineIterator lineIterator = new LineIterator(reader);
            StringBuilder jsonStringBuilder = new StringBuilder();

            while (lineIterator.hasNext()) {
                jsonStringBuilder.append(lineIterator.nextLine());
            }
            JsonResponseError error = JsonConverter.getError(jsonStringBuilder.toString());
            throw new ClientProtocolException(error.getMessage());
        case 401:
            throw new ClientProtocolException("Status 401 - Bad credentials!");
        case 403:
            throw new ClientProtocolException("Status 403 - You must be an admin to execute this command!");
        case 404:
            reader = null;
            reader = new InputStreamReader(response.getEntity().getContent());
            lineIterator = new LineIterator(reader);
            jsonStringBuilder = new StringBuilder();

            while (lineIterator.hasNext()) {
                jsonStringBuilder.append(lineIterator.nextLine());
            }
            error = JsonConverter.getError(jsonStringBuilder.toString());
            throw new ClientProtocolException(error.getMessage());
        default:
            reader = null;
            reader = new InputStreamReader(response.getEntity().getContent());
            lineIterator = new LineIterator(reader);
            jsonStringBuilder = new StringBuilder();

            while (lineIterator.hasNext()) {
                jsonStringBuilder.append(lineIterator.nextLine());
            }
            error = JsonConverter.getError(jsonStringBuilder.toString());
            throw new ClientProtocolException(error.getMessage());
        }
    }

}

From source file:com.optimizely.ab.config.HttpProjectConfigManager.java

public String getDatafileFromResponse(HttpResponse response) throws NullPointerException, IOException {
    StatusLine statusLine = response.getStatusLine();

    if (statusLine == null) {
        throw new ClientProtocolException("unexpected response from event endpoint, status is null");
    }/*from  w ww .  j a v a 2 s . co  m*/

    int status = statusLine.getStatusCode();

    // Datafile has not updated
    if (status == HttpStatus.SC_NOT_MODIFIED) {
        logger.debug("Not updating ProjectConfig as datafile has not updated since " + datafileLastModified);
        return null;
    }

    if (status >= 200 && status < 300) {
        // read the response, so we can close the connection
        HttpEntity entity = response.getEntity();
        Header lastModifiedHeader = response.getFirstHeader(HttpHeaders.LAST_MODIFIED);
        if (lastModifiedHeader != null) {
            datafileLastModified = lastModifiedHeader.getValue();
        }
        return EntityUtils.toString(entity, "UTF-8");
    } else {
        throw new ClientProtocolException("unexpected response from event endpoint, status: " + status);
    }
}

From source file:com.ny.apps.executor.TencentWeiboOAuth2.java

public String getCode(String APPKEY, String APPSECRET) throws Exception {
    String code = null;// w  w  w.  ja  va  2 s .c  o  m

    CloseableHttpClient client = HttpClients.createDefault();

    HttpGet httpGet = new HttpGet(prepareGetUrl());

    System.out.println(prepareGetUrl().toASCIIString());

    logger.info("executing request " + httpGet.getURI());

    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
        @Override
        public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode >= 200 && statusCode < 300) {
                HttpEntity entity = response.getEntity();
                return entity == null ? null : EntityUtils.toString(entity);
            } else {
                throw new ClientProtocolException("Unexpected response status: " + statusCode);
            }
        }
    };

    try {
        String responseBody = client.execute(httpGet, responseHandler);
        System.out.println("----------------------------------------");
        System.out.println(responseBody);
        System.out.println("----------------------------------------");
    } finally {
        client.close();
    }

    return code;
}

From source file:es.uned.dia.jcsombria.softwarelinks.transport.HttpTransport.java

public Object send(String request) throws Exception {
    Object response = null;// ww  w.j  a v  a 2 s  . c o m
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpPost httppost = new HttpPost(serverURL.toString());
        httppost.setEntity(new StringEntity(request));
        // Create a custom response handler
        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
            public String handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            }
        };
        String responseBody = httpclient.execute(httppost, responseHandler);
        response = responseBody;
    } finally {
        httpclient.close();
    }
    return response;
}

From source file:org.opendaylight.infrautils.diagstatus.shell.HttpClient.java

public HttpResponse sendRequest(HttpRequest request) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    if (httpclient == null) {
        throw new ClientProtocolException("Couldn't create an HTTP client");
    }//from w w  w  .jav a 2s. c o m
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(request.getTimeout())
            .setConnectTimeout(request.getTimeout()).build();
    HttpRequestBase httprequest;
    String method = request.getMethod();
    if (method.equalsIgnoreCase("GET")) {
        httprequest = new HttpGet(request.getUri());
    } else if (method.equalsIgnoreCase("POST")) {
        httprequest = new HttpPost(request.getUri());
        if (request.getEntity() != null) {
            StringEntity sentEntity = new StringEntity(request.getEntity());
            sentEntity.setContentType(request.getContentType());
            ((HttpEntityEnclosingRequestBase) httprequest).setEntity(sentEntity);
        }
    } else if (method.equalsIgnoreCase("PUT")) {
        httprequest = new HttpPut(request.getUri());
        if (request.getEntity() != null) {
            StringEntity sentEntity = new StringEntity(request.getEntity());
            sentEntity.setContentType(request.getContentType());
            ((HttpEntityEnclosingRequestBase) httprequest).setEntity(sentEntity);
        }
    } else if (method.equalsIgnoreCase("DELETE")) {
        httprequest = new HttpDelete(request.getUri());
    } else {
        httpclient.close();
        throw new IllegalArgumentException(
                "This profile class only supports GET, POST, PUT, and DELETE methods");
    }
    httprequest.setConfig(requestConfig);
    // add request headers
    Iterator<String> headerIterator = request.getHeaders().keySet().iterator();
    while (headerIterator.hasNext()) {
        String header = headerIterator.next();
        Iterator<String> valueIterator = request.getHeaders().get(header).iterator();
        while (valueIterator.hasNext()) {
            httprequest.addHeader(header, valueIterator.next());
        }
    }
    CloseableHttpResponse response = httpclient.execute(httprequest);
    try {
        int httpResponseCode = response.getStatusLine().getStatusCode();
        HashMap<String, List<String>> headerMap = new HashMap<>();
        // copy response headers
        HeaderIterator it = response.headerIterator();
        while (it.hasNext()) {
            Header nextHeader = it.nextHeader();
            String name = nextHeader.getName();
            String value = nextHeader.getValue();
            if (headerMap.containsKey(name)) {
                headerMap.get(name).add(value);
            } else {
                List<String> list = new ArrayList<>();
                list.add(value);
                headerMap.put(name, list);
            }
        }
        if (httpResponseCode > 299) {
            return new HttpResponse(httpResponseCode, response.getStatusLine().getReasonPhrase(), headerMap);
        }
        Optional<HttpEntity> receivedEntity = Optional.ofNullable(response.getEntity());
        String httpBody = receivedEntity.isPresent() ? EntityUtils.toString(receivedEntity.get()) : null;
        return new HttpResponse(response.getStatusLine().getStatusCode(), httpBody, headerMap);
    } finally {
        response.close();
    }
}

From source file:com.qwazr.utils.http.HttpUtils.java

/**
 * Check if the entity has the expected mime type. The charset is not
 * checked.// w  w  w. jav  a2s.c  o m
 *
 * @param response            The response to check
 * @param expectedContentType The expected content type
 * @return the entity from the response body
 * @throws ClientProtocolException if the response does not contains any entity
 */
public static HttpEntity checkIsEntity(HttpResponse response, ContentType expectedContentType)
        throws ClientProtocolException {
    if (response == null)
        throw new ClientProtocolException("No response");
    HttpEntity entity = response.getEntity();
    if (entity == null)
        throw new ClientProtocolException("Response does not contains any content entity");
    if (expectedContentType == null)
        return entity;
    ContentType contentType = ContentType.get(entity);
    if (contentType == null)
        throw new HttpResponseEntityException(response, "Unknown content type");
    if (!expectedContentType.getMimeType().equals(contentType.getMimeType()))
        throw new HttpResponseEntityException(response,
                StringUtils.fastConcat("Wrong content type: ", contentType.getMimeType()));
    return entity;
}

From source file:es.uned.dia.jcsombria.model_elements.softwarelinks.nodejs.HttpTransport.java

public Object send(String request) throws Exception {
    Object response = null;/* w w w.  j av  a  2 s  .c  o m*/
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpPost httppost = new HttpPost(serverURL.toString());
        System.out.println("Executing request " + httppost.getRequestLine());
        System.out.println(request);
        httppost.setEntity(new StringEntity(request));
        // Create a custom response handler
        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
            public String handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            }
        };
        String responseBody = httpclient.execute(httppost, responseHandler);
        response = responseBody;
    } finally {
        httpclient.close();
    }
    return response;
}

From source file:org.apache.solr.kelvin.URLQueryPerformer.java

@Override
protected Object performTestQueries(ITestCase testCase, Properties queryParams) throws Exception {
    URIBuilder uriBuilder = new URIBuilder(this.baseUrl);
    for (String paramName : queryParams.stringPropertyNames()) {
        uriBuilder.setParameter(paramName, queryParams.getProperty(paramName));
    }/*from  www .j  a  v  a  2 s .c  o m*/
    URI uri = uriBuilder.build();
    HttpGet httpget = new HttpGet(uri);

    System.out.println("executing request " + httpget.getURI());

    // Create a custom response handler
    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

        public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
            int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status < 300) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            } else {
                throw new ClientProtocolException("Unexpected response status: " + status);
            }
        }

    };
    String responseBody = httpclient.execute(httpget, responseHandler);

    return responseBody;
}

From source file:ca.sqlpower.dao.json.JSONHttpMessageSender.java

public void flush() throws SPPersistenceException {
    try {//from  w  w  w  . j a  v  a  2 s .c  o m
        URI serverURI = getServerURI();
        HttpPost postRequest = new HttpPost(serverURI);
        postRequest.setEntity(new StringEntity(messageArray.toString()));
        postRequest.setHeader("Content-Type", "application/json");
        HttpUriRequest request = postRequest;
        getHttpClient().execute(request, new ResponseHandler<Void>() {
            public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                StatusLine statusLine = response.getStatusLine();
                if (statusLine.getStatusCode() >= 400) {
                    throw new ClientProtocolException("HTTP Post request returned an error: " + "Code = "
                            + statusLine.getStatusCode() + ", " + "Reason = " + statusLine.getReasonPhrase());
                }
                return null;
            }
        });
    } catch (URISyntaxException e) {
        throw new SPPersistenceException(null, e);
    } catch (ClientProtocolException e) {
        throw new SPPersistenceException(null, e);
    } catch (IOException e) {
        throw new SPPersistenceException(null, e);
    } finally {
        clearMessageArray();
    }
}

From source file:me.ixfan.wechatkit.token.AccessTokenResponseHandler.java

/**
 * Response handler of WeChat access_token request.
 *
 * @param response/*w w  w  . j av a  2s  . c  o  m*/
 * @return
 * @throws IOException
 */
@Override
public AccessToken handleResponse(HttpResponse response) throws IOException {
    StatusLine status = response.getStatusLine();
    HttpEntity entity = response.getEntity();

    if (status.getStatusCode() >= 300) {
        throw new HttpResponseException(status.getStatusCode(), status.getReasonPhrase());
    }
    if (null == entity) {
        logger.error("Exception occurred while obtaining access_token, there's no data in the response.");
        throw new ClientProtocolException("Empty HTTP response");
    }

    ContentType contentType = ContentType.getOrDefault(entity);
    Charset charset = contentType.getCharset();
    if (null == charset) {
        charset = StandardCharsets.UTF_8;
    }
    Reader reader = new InputStreamReader(entity.getContent(), charset);
    JsonObject jsonObject = new JsonParser().parse(reader).getAsJsonObject();

    logger.debug("obtained access_token: " + jsonObject.toString());

    Map<String, String> keyValues = new HashMap<>();
    for (Map.Entry<String, JsonElement> element : jsonObject.entrySet()) {
        keyValues.put(element.getKey(), element.getValue().getAsString());
    }

    AccessToken accessToken = new AccessToken();
    if (null != keyValues.get("access_token")) {
        accessToken.setAccessToken(keyValues.get("access_token"));
        accessToken.setExpiresIn(Long.parseLong(keyValues.get("expires_in")));
    } else {
        logger.error("Obtaining access_token failed, errcode:{}, errmsg:{}", keyValues.get("errcode"),
                keyValues.get("errmsg"));
    }

    return accessToken;
}