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:com.wallpaper.core.loopj.android.http.AsyncHttpResponseHandler.java

void sendResponseMessage(HttpResponse response) {
    StatusLine status = response.getStatusLine();
    String responseBody = null;/*from   ww w .  jav  a2 s. co m*/
    try {
        HttpEntity entity = null;
        HttpEntity temp = response.getEntity();
        if (temp != null) {
            entity = new BufferedHttpEntity(temp);
            responseBody = EntityUtils.toString(entity, "UTF-8");
        }
    } catch (IOException e) {
        sendFailureMessage(e, (String) null);
    }

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

From source file:org.carrot2.source.xml.RemoteXmlSimpleSearchEngineBase.java

/**
 * Loads a {@link ProcessingResult} from the provided remote URL, applying XSLT
 * transform if specified. This method can handle gzip-compressed streams if supported
 * by the data source./*from   www . java 2 s. c o  m*/
 * 
 * @param metadata if a non-<code>null</code> map is provided, request metadata will
 *            be put into the map.
 * @param user if not <code>null</code>, the user name to use for HTTP Basic
 *            Authentication
 * @param password if not <code>null</code>, the password to use for HTTP Basic
 *            Authentication
 */
protected ProcessingResult loadProcessingResult(String url, Templates stylesheet,
        Map<String, String> xsltParameters, Map<String, Object> metadata, String user, String password,
        HttpRedirectStrategy redirectStrategy) throws Exception {
    final HttpUtils.Response response = HttpUtils.doGET(url, null, null, user, password,
            xmlDocumentSourceHelper.timeout * 1000, redirectStrategy.value());

    final InputStream carrot2XmlStream = response.getPayloadAsStream();
    final int statusCode = response.status;

    if (statusCode == HttpStatus.SC_OK) {
        metadata.put(SearchEngineResponse.COMPRESSION_KEY, response.compression);
        return xmlDocumentSourceHelper.loadProcessingResult(carrot2XmlStream, stylesheet, xsltParameters);
    } else {
        throw new HttpResponseException(statusCode, response.statusMessage);
    }
}

From source file:com.esri.geoportal.commons.http.BotsHttpClient.java

private void adviseRobotsTxt(URI u) throws IOException {
    if (bots != null) {
        String url = getRelativePath(u);
        LOG.debug(String.format("Evaluating access to %s using robots.txt", u));
        Access access = requestAccess(bots, url);
        if (!access.hasAccess()) {
            LOG.info(String.format("Access to %s disallowed by robots.txt", u));
            throw new HttpResponseException(403, String.format("Access to %s disallowed by robots.txt", url));
        }//  w w  w  .j  a  v  a2 s  . c o  m
        LOG.debug(String.format("Access to %s allowed by robots.txt", u));
        CrawlLocker.getInstance().enterServer(getProtocolHostPort(u), resolveThrottleDelay());
    }
}

From source file:com.unifonic.sdk.resources.http.AccountResourceImpl.java

@Override
public ResponseModel<Voids> deleteSenderID(String senderID) throws IOException {
    ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
    param.add(new BasicNameValuePair(PARAM_SENDER_ID, senderID));
    OTSRestResponse response = sendRequest(accountUrl.urlDeleteSenderID(), param);
    if (response.getStatusCode() < 400) {
        Type type = new TypeToken<ResponseModel<Voids>>() {
        }.getType();//from   ww w.  j a va 2  s  . c o m
        ResponseModel<Voids> respData = GSON.fromJson(response.getData(), type);
        return respData;
    } else if (response.getStatusCode() == 400) {
        ResponseModel<Voids> respData = GSON.fromJson(response.getData(), ResponseModel.class);
        return respData;
    } else {
        throw new HttpResponseException(response.getStatusCode(), response.getReasonPhrase());
    }
}

From source file:com.example.restexpmongomvn.controller.VehicleControllerTest.java

/**
 * Test of read method, of class VehicleController.
 * @throws com.fasterxml.jackson.core.JsonProcessingException
 * @throws java.io.IOException/* w  w  w . j av  a2  s. c  om*/
 */
@Test
public void testRead() throws JsonProcessingException, IOException {
    System.out.println("read");

    Vehicle testVehicle = new Vehicle(2015, "Test", "Vehicle", Color.Red, "4-Door Sedan");
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setSerializationInclusion(Include.NON_EMPTY);
    String testVehicleString = objectMapper.writeValueAsString(testVehicle);

    StringEntity postEntity = new StringEntity(testVehicleString,
            ContentType.create("application/json", "UTF-8"));
    postEntity.setChunked(true);

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httppost = new HttpPost(BASE_URL + "/restexpress/vehicles");
    httppost.setEntity(postEntity);
    CloseableHttpResponse response = httpclient.execute(httppost);

    String responseString = new BasicResponseHandler().handleResponse(response);
    responseString = responseString.replaceAll("^\"|\"$", "");

    // Get vehicle based on MongoDB id
    HttpGet httpget = new HttpGet(BASE_URL + "/restexpress/vehicle/" + responseString);
    CloseableHttpResponse response2 = httpclient.execute(httpget);

    String responseString2 = new BasicResponseHandler().handleResponse(response2);

    ResponseHandler<Vehicle> rh = new ResponseHandler<Vehicle>() {

        @Override
        public Vehicle handleResponse(final HttpResponse response) throws IOException {
            StatusLine statusLine = response.getStatusLine();
            HttpEntity entity = response.getEntity();
            if (statusLine.getStatusCode() >= 300) {
                throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
            }
            if (entity == null) {
                throw new ClientProtocolException("Response contains no content");
            }
            Gson gson = new GsonBuilder().setPrettyPrinting().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
                    .create();
            ContentType contentType = ContentType.getOrDefault(entity);
            Charset charset = contentType.getCharset();
            Reader reader = new InputStreamReader(entity.getContent(), "UTF-8");

            //                String inputStreamString = new Scanner(entity.getContent(), "UTF-8").useDelimiter("\\A").next();
            //                System.out.println(inputStreamString);

            return gson.fromJson(reader, Vehicle.class);
        }
    };
    Vehicle vehicle = httpclient.execute(httpget, rh);
    System.out.println("b");

    //        MongodbEntityRepository<Vehicle> vehicleRepository;
    //        VehicleController instance = new VehicleController(vehicleRepository);
    //        Vehicle result = instance.read(request, response);
    //        assertEquals(parseMongoId(responseString), true);
}

From source file:org.cloudsmith.stackhammer.api.client.StackHammerClient.java

private <V> V executeRequest(final HttpRequestBase request, final Class<V> type) throws IOException {

    ResponseHandler<V> responseHandler = new ResponseHandler<V>() {
        @Override//from  w ww.ja v  a 2 s  . co m
        public V handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            StatusLine statusLine = response.getStatusLine();
            int code = statusLine.getStatusCode();
            if (code >= 300)
                throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());

            HttpEntity entity = response.getEntity();
            if (isOk(code))
                return parseJson(getStream(entity), type);

            throw createException(getStream(entity), code, statusLine.getReasonPhrase());
        }
    };

    return httpClient.execute(request, responseHandler);
}

From source file:org.opentestsystem.shared.permissions.rest.APIHandler.java

@RequestMapping(value = "permission", method = RequestMethod.GET)
@ResponseBody/* www  . j  a v a 2  s .  com*/
//@Secured({ "ROLE_Administrator Read" })
public ReturnStatus<List<Permission>> getPermission(
        @RequestParam(value = "role", required = false) String roleName,
        @RequestParam(value = "component", required = false) String componentName)
        throws PermissionsRetrievalException, HttpResponseException {
    List<Permission> listP;

    if (!StringUtils.isEmpty(roleName) && !StringUtils.isEmpty(componentName)) {
        listP = getPersister().getPermissionByRoleAndComponent(roleName, componentName);
        if (listP.size() <= 0) {
            throw new HttpResponseException(404, String
                    .format("No permission by rolename:%s and component name:%s.", roleName, componentName));
        }
    } else if (!StringUtils.isEmpty(componentName)) {
        listP = getPersister().getPermissionsByComponent(componentName);
        if (listP.size() <= 0) {
            throw new HttpResponseException(404,
                    String.format("No permission by component name:%s.", componentName));
        }
    } else {
        listP = getPersister().getAllPermissions();
    }

    ReturnStatus<List<Permission>> status = new ReturnStatus<List<Permission>>(StatusEnum.SUCCESS, null);
    status.setValue(listP);
    return status;
}

From source file:com.my.cloudcontact.http.HttpHandler.java

private void handleResponse(HttpUriRequest request, HttpResponse response) {
    StatusLine status = response.getStatusLine();
    if (status.getStatusCode() >= 300) {
        String errorMsg = "response status error code:" + status.getStatusCode();
        if (status.getStatusCode() == 416 && isResume) {
            errorMsg += " \n maybe you have download complete.";
        }/*ww w  .  ja  va2 s  .  c o m*/
        publishProgress(UPDATE_FAILURE,
                new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()),
                status.getStatusCode(), errorMsg);
    } else {
        try {

            //  ??
            if (mCheckResponse != null) {
                //
                if (mCheckResponse.checkResponse(request, response))
                    return;
            }

            // ?
            HttpEntity entity = response.getEntity();
            Object responseBody = null;
            if (entity != null) {
                time = SystemClock.uptimeMillis();
                if (targetUrl != null) {
                    responseBody = mFileEntityHandler.handleEntity(entity, this, targetUrl, isResume);
                } else {
                    responseBody = mStrEntityHandler.handleEntity(entity, this, charset);
                }
            }
            publishProgress(UPDATE_SUCCESS, responseBody, request, response);
        } catch (IOException e) {
            publishProgress(UPDATE_FAILURE, e, 0, e.getMessage());
        } catch (SeverRequestException e) {
            publishProgress(UPDATE_FAILURE, e, 0, e.getMessage());
        }

    }
}

From source file:cz.incad.kramerius.utils.solr.SolrUtils.java

public static InputStream getSolrDataInternal(String query, String format) throws IOException {
    String solrHost = KConfiguration.getInstance().getSolrHost();
    String uri = solrHost + "/select?" + query;
    if (!uri.endsWith("&")) {
        uri = uri + "&wt=" + format;
    } else {//w  w w.j  av  a 2  s  .c  o m
        uri = uri + "wt=" + format;
    }
    HttpGet httpGet = new HttpGet(uri);
    CloseableHttpClient client = HttpClients.createDefault();
    HttpResponse response = client.execute(httpGet);
    if (response.getStatusLine().getStatusCode() == 200) {
        return response.getEntity().getContent();
    } else {
        throw new HttpResponseException(response.getStatusLine().getStatusCode(),
                response.getStatusLine().getReasonPhrase());
    }

}

From source file:org.neo4j.ogm.drivers.http.request.HttpRequest.java

public static CloseableHttpResponse execute(CloseableHttpClient httpClient, HttpRequestBase request,
        Credentials credentials) throws HttpRequestException {

    LOGGER.debug("Thread: {}, request: {}", Thread.currentThread().getId(), request);

    CloseableHttpResponse response;// ww  w .  j  a  v a2s .  c o m

    request.setHeader(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
    request.setHeader(new BasicHeader(HTTP.USER_AGENT, "neo4j-ogm.java/2.0"));
    request.setHeader(new BasicHeader("Accept", "application/json;charset=UTF-8"));

    HttpAuthorization.authorize(request, credentials);

    // use defaults: 3 retries, 2 second wait between attempts
    RetryOnExceptionStrategy retryStrategy = new RetryOnExceptionStrategy();

    while (retryStrategy.shouldRetry()) {

        try {

            response = httpClient.execute(request);

            StatusLine statusLine = response.getStatusLine();
            HttpEntity responseEntity = response.getEntity();

            if (statusLine.getStatusCode() >= 300) {
                String responseText = statusLine.getReasonPhrase();
                if (responseEntity != null) {
                    responseText = parseError(EntityUtils.toString(responseEntity));
                    LOGGER.warn("Thread: {}, response: {}", Thread.currentThread().getId(), responseText);
                }
                throw new HttpResponseException(statusLine.getStatusCode(), responseText);
            }
            if (responseEntity == null) {
                throw new ClientProtocolException("Response contains no content");
            }

            return response; // don't close response yet, it is not consumed!
        }

        // if we didn't get a response at all, try again
        catch (NoHttpResponseException nhre) {
            LOGGER.warn("Thread: {}, No response from server:  Retrying in {} milliseconds, retries left: {}",
                    Thread.currentThread().getId(), retryStrategy.getTimeToWait(),
                    retryStrategy.numberOfTriesLeft);
            retryStrategy.errorOccurred();
        } catch (RetryException re) {
            throw new HttpRequestException(request, re);
        } catch (ClientProtocolException uhe) {
            throw new ConnectionException(request.getURI().toString(), uhe);
        } catch (IOException ioe) {
            throw new HttpRequestException(request, ioe);
        }

        // here we catch any exception we throw above (plus any we didn't throw ourselves),
        // log the problem, close any connection held by the request
        // and then rethrow the exception to the caller.
        catch (Exception exception) {
            LOGGER.warn("Thread: {}, exception: {}", Thread.currentThread().getId(),
                    exception.getCause().getLocalizedMessage());
            request.releaseConnection();
            throw exception;
        }
    }
    throw new RuntimeException("Fatal Exception: Should not have occurred!");
}