Java Code Examples for org.apache.http.StatusLine#getStatusCode()
The following examples show how to use
org.apache.http.StatusLine#getStatusCode() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AsyncHttpResponseHandler.java From Android-Basics-Codes with Artistic License 2.0 | 6 votes |
@Override public void sendResponseMessage(HttpResponse response) throws IOException { // do not process if request has been cancelled if (!Thread.currentThread().isInterrupted()) { StatusLine status = response.getStatusLine(); byte[] responseBody; responseBody = getResponseData(response.getEntity()); // additional cancellation check as getResponseData() can take non-zero time to process if (!Thread.currentThread().isInterrupted()) { if (status.getStatusCode() >= 300) { sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), responseBody, new HttpResponseException(status.getStatusCode(), status.getReasonPhrase())); } else { sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody); } } } }
Example 2
Source File: ToopherAPI.java From oxAuth with MIT License | 6 votes |
@Override public JSONObject handleResponse(HttpResponse response) throws ClientProtocolException, IOException { StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() >= 300) { throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase()); } HttpEntity entity = response.getEntity(); // TODO: check entity == null String json = EntityUtils.toString(entity); try { return (JSONObject) new JSONTokener(json).nextValue(); } catch (JSONException e) { throw new ClientProtocolException("Could not interpret response as JSON", e); } }
Example 3
Source File: PGPKeysServerClient.java From pgpverify-maven-plugin with Apache License 2.0 | 6 votes |
/** * Verify that the provided response was successful, and then copy the response to the given * output buffer. * * <p>If the response was not successful (e.g. not a "200 OK") status code, or the response * payload was empty, an {@link IOException} will be thrown. * * @param response * A representation of the response from the server. * @param outputStream * The stream to which the response data will be written. * * @throws IOException * If the response was unsuccessful, did not contain any data, or could not be written * completely to the target output stream. */ private static void processKeyResponse(CloseableHttpResponse response, OutputStream outputStream) throws IOException { final StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() == HttpStatus.SC_NOT_FOUND) { throw new PGPKeyNotFound(); } if (statusLine.getStatusCode() == HttpStatus.SC_OK) { final HttpEntity responseEntity = response.getEntity(); if (responseEntity == null) { throw new IOException("No response body returned."); } else { try (InputStream inputStream = responseEntity.getContent()) { ByteStreams.copy(inputStream, outputStream); } } } else { throw new IOException("PGP server returned an error: " + statusLine); } }
Example 4
Source File: HttpClientAdapter.java From davmail with GNU General Public License v2.0 | 6 votes |
/** * Build Http Exception from method status * * @param method Http Method * @return Http Exception */ public static HttpResponseException buildHttpResponseException(HttpRequestBase method, StatusLine statusLine) { int status = statusLine.getStatusCode(); StringBuilder message = new StringBuilder(); message.append(status).append(' ').append(statusLine.getReasonPhrase()); message.append(" at ").append(method.getURI()); if (method instanceof HttpCopy || method instanceof HttpMove) { message.append(" to ").append(method.getFirstHeader("Destination")); } // 440 means forbidden on Exchange if (status == 440) { return new LoginTimeoutException(message.toString()); } else if (status == HttpStatus.SC_FORBIDDEN) { return new HttpForbiddenException(message.toString()); } else if (status == HttpStatus.SC_NOT_FOUND) { return new HttpNotFoundException(message.toString()); } else if (status == HttpStatus.SC_PRECONDITION_FAILED) { return new HttpPreconditionFailedException(message.toString()); } else if (status == HttpStatus.SC_INTERNAL_SERVER_ERROR) { return new HttpServerErrorException(message.toString()); } else { return new HttpResponseException(status, message.toString()); } }
Example 5
Source File: InfluxDBReporterTest.java From metrics with Apache License 2.0 | 5 votes |
@Test public void testReporting(@Mocked CloseableHttpClient httpClient, @Mocked CloseableHttpResponse closeableHttpResponse, @Mocked StatusLine statusLine) throws InterruptedException, IOException { new Expectations() {{ httpClient.execute((HttpUriRequest) any); result = closeableHttpResponse; closeableHttpResponse.getStatusLine(); result = statusLine; statusLine.getStatusCode(); result = 200; }}; MetricRegistry registry = new MetricRegistry(); InfluxDBReporter reporter = InfluxDBReporter.builder() .withBaseUri(URI.create("http://localhost:8086")) .withDatabase("test") .build(); registry.addReporter(reporter); Counter counter = registry.counter("counter"); counter.inc("tag", "value"); Thread.sleep(3000); new Verifications() {{ httpClient.execute((HttpUriRequest) any); times = 1; }}; }
Example 6
Source File: ApacheGatewayConnection.java From vespa with Apache License 2.0 | 5 votes |
private void verifyServerResponseCode(HttpResponse response) throws ServerResponseException { StatusLine statusLine = response.getStatusLine(); // We use code 261-299 to report errors related to internal transitive errors that the tenants should not care // about to avoid masking more serious errors. int statusCode = statusLine.getStatusCode(); if (statusCode > 199 && statusCode < 260) { return; } if (statusCode == 299) { throw new ServerResponseException(429, "Too many requests."); } String message = tryGetDetailedErrorMessage(response) .orElseGet(statusLine::getReasonPhrase); throw new ServerResponseException(statusLine.getStatusCode(), message); }
Example 7
Source File: OpenTSDBReporterTest.java From metrics with Apache License 2.0 | 5 votes |
@Test public void testUploadFailedServerError(@Mocked CloseableHttpClient httpClient, @Mocked CloseableHttpResponse closeableHttpResponse, @Mocked StatusLine statusLine, @Capturing Logger logger) throws IOException, InterruptedException { new Expectations() {{ httpClient.execute((HttpUriRequest) any); result = closeableHttpResponse; closeableHttpResponse.getStatusLine(); result = statusLine; statusLine.getStatusCode(); result = 500; }}; MetricRegistry registry = new MetricRegistry(); OpenTSDBReporter reporter = makeReporter(); registry.addReporter(reporter); Counter counter = registry.counter("counter"); counter.inc("tag", "value"); Thread.sleep(3000); new Verifications() {{ logger.error(anyString, withInstanceOf(IllegalStateException.class)); }}; }
Example 8
Source File: NetEaseResponseHandler.java From YiBo with Apache License 2.0 | 5 votes |
public String handleResponse(final HttpResponse response) throws HttpResponseException, IOException { StatusLine statusLine = response.getStatusLine(); HttpEntity entity = response.getEntity(); String responseString = (entity == null ? null : EntityUtils.toString(entity)); logger.debug("NetEaseResponseHandler : {}", responseString); if (statusLine.getStatusCode() >= 300) { throw NetEaseErrorAdaptor.parseError(responseString); } return responseString; }
Example 9
Source File: OpenTSDBReporterTest.java From metrics with Apache License 2.0 | 5 votes |
@Test public void testReportingBaseUriWithPath(@Mocked CloseableHttpClient httpClient, @Mocked CloseableHttpResponse closeableHttpResponse, @Mocked StatusLine statusLine) throws InterruptedException, IOException { new Expectations() {{ httpClient.execute((HttpUriRequest) any); result = closeableHttpResponse; closeableHttpResponse.getStatusLine(); result = statusLine; statusLine.getStatusCode(); result = 200; }}; MetricRegistry registry = new MetricRegistry(); OpenTSDBReporter reporter = OpenTSDBReporter.builder() .withBaseUri(URI.create("http://localhost:4242/some/path/")) .build(); registry.addReporter(reporter); Counter counter = registry.counter("counter"); counter.inc("tag", "value"); Thread.sleep(3000); new Verifications() {{ HttpUriRequest request; httpClient.execute(request = withCapture()); assertEquals("/some/path/api/v1/put", request.getURI().getPath()); times = 1; }}; }
Example 10
Source File: HttpUtil.java From wechat-mp-sdk with Apache License 2.0 | 5 votes |
@Override public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException { final StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() >= 300) { throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase()); } final HttpEntity entity = response.getEntity(); if (entity != null) { return EntityUtils.toString(entity, "UTF-8"); } return StringUtils.EMPTY; }
Example 11
Source File: OpenTSDBHttpClient.java From metrics with Apache License 2.0 | 5 votes |
void flush() throws IOException { if (currentBatchSize < 1) { return; } // flush writer.write(']'); writer.flush(); HttpPost httpPost = new HttpPost(dbUri); httpPost.setEntity(new ByteArrayEntity(buffer.toByteArray(), ContentType.APPLICATION_JSON)); final StatusLine status; CloseableHttpResponse response = null; try { response = httpClient.execute(httpPost); status = response.getStatusLine(); // CLOVER:OFF // Just tracing. if (LOG.isTraceEnabled()) { LOG.trace("Response from OpenTSDB [{}] ", EntityUtils.toString(response.getEntity())); } // CLOVER:ON } finally { if (response != null) { EntityUtils.consumeQuietly(response.getEntity()); } // reset our buffer and batch size currentBatchSize = 0; buffer.reset(); writer.write('['); } if (status.getStatusCode() / 100 != 2) { throw new IllegalStateException(String.format( "Failed to write metrics to OpenTSDB '%d' - '%s'", status.getStatusCode(), status.getReasonPhrase())); } }
Example 12
Source File: ApacheHttpClient.java From feign with Apache License 2.0 | 5 votes |
Response toFeignResponse(HttpResponse httpResponse, Request request) throws IOException { StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); String reason = statusLine.getReasonPhrase(); Map<String, Collection<String>> headers = new HashMap<String, Collection<String>>(); for (Header header : httpResponse.getAllHeaders()) { String name = header.getName(); String value = header.getValue(); Collection<String> headerValues = headers.get(name); if (headerValues == null) { headerValues = new ArrayList<String>(); headers.put(name, headerValues); } headerValues.add(value); } return Response.builder() .status(statusCode) .reason(reason) .headers(headers) .request(request) .body(toFeignBody(httpResponse)) .build(); }
Example 13
Source File: HttpUtil.java From thym with Eclipse Public License 1.0 | 5 votes |
/** * Returns input stream from defined url. Connection uses cache and eclipse proxy, if defined * @param url * @return url input stream * @throws IOException */ public static InputStream getHttpStream(String url) throws IOException{ URI target = URI.create(url); CloseableHttpClient client = getHttpClient(target); HttpGet get = new HttpGet(target); HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); StatusLine line = response.getStatusLine(); if(line.getStatusCode() != 200){ throw new IOException("HTTP response status is "+line.getStatusCode()); } return entity.getContent(); }
Example 14
Source File: BounceProxyPerformanceReporter.java From joynr with Apache License 2.0 | 5 votes |
/** * Sends an HTTP request to the monitoring service to report performance * measures of a bounce proxy instance. * * @throws IOException */ private void sendPerformanceReportAsHttpRequest() throws IOException { final String url = bounceProxyControllerUrl.buildReportPerformanceUrl(); logger.debug("Using monitoring service URL: {}", url); Map<String, Integer> performanceMap = bounceProxyPerformanceMonitor.getAsKeyValuePairs(); String serializedMessage = objectMapper.writeValueAsString(performanceMap); HttpPost postReportPerformance = new HttpPost(url.trim()); // using http apache constants here because JOYNr constants are in // libjoynr which should not be included here postReportPerformance.addHeader(HttpHeaders.CONTENT_TYPE, "application/json"); postReportPerformance.setEntity(new StringEntity(serializedMessage, "UTF-8")); CloseableHttpResponse response = null; try { response = httpclient.execute(postReportPerformance); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode != HttpURLConnection.HTTP_NO_CONTENT) { logger.error("Failed to send performance report: {}", response); throw new JoynrHttpException(statusCode, "Failed to send performance report."); } } finally { if (response != null) { response.close(); } } }
Example 15
Source File: MCRDataciteClient.java From mycore with GNU General Public License v3.0 | 5 votes |
public URI resolveDOI(final MCRDigitalObjectIdentifier doiParam) throws MCRPersistentIdentifierException { URI requestURI = getRequestURI("/doi/" + doiParam.asString()); HttpGet get = new HttpGet(requestURI); try (CloseableHttpClient httpClient = getHttpClient()) { CloseableHttpResponse response = httpClient.execute(get); HttpEntity entity = response.getEntity(); StatusLine statusLine = response.getStatusLine(); switch (statusLine.getStatusCode()) { case HttpStatus.SC_OK: try (Scanner scanner = new Scanner(entity.getContent(), "UTF-8")) { String uriString = scanner.nextLine(); return new URI(uriString); } case HttpStatus.SC_NO_CONTENT: throw new MCRIdentifierUnresolvableException(doiParam.asString(), "The identifier " + doiParam.asString() + " is currently not resolvable"); case HttpStatus.SC_NOT_FOUND: throw new MCRIdentifierUnresolvableException(doiParam.asString(), "The identifier " + doiParam.asString() + " was not found in the Datacenter!"); case HttpStatus.SC_UNAUTHORIZED: throw new MCRDatacenterAuthenticationException(); case HttpStatus.SC_INTERNAL_SERVER_ERROR: throw new MCRDatacenterException( String.format(Locale.ENGLISH, "Datacenter error while resolving doi: \"%s\" : %s", doiParam.asString(), getStatusString(response))); default: throw new MCRDatacenterException(String.format(Locale.ENGLISH, "Unknown error while resolving doi: \"%s\" : %s", doiParam.asString(), getStatusString(response))); } } catch (IOException | URISyntaxException ex) { throw new MCRDatacenterException( String.format(Locale.ENGLISH, "Unknown error while resolving doi: \"%s\"", doiParam.asString()), ex); } }
Example 16
Source File: MCRDataciteClient.java From mycore with GNU General Public License v3.0 | 5 votes |
/** * * @param doi the doi * @return the resolved metadata of the doi * @throws MCRDatacenterAuthenticationException if the authentication is wrong * @throws MCRIdentifierUnresolvableException if the doi is not valid or can not be resolved * @throws JDOMException if the metadata is empty or not a valid xml document * @throws MCRDatacenterException if there is something wrong with the communication with the datacenter */ public Document resolveMetadata(final MCRDigitalObjectIdentifier doi) throws MCRDatacenterAuthenticationException, MCRIdentifierUnresolvableException, JDOMException, MCRDatacenterException { URI requestURI = getRequestURI("/metadata/" + doi.asString()); HttpGet get = new HttpGet(requestURI); try (CloseableHttpClient httpClient = getHttpClient()) { CloseableHttpResponse response = httpClient.execute(get); HttpEntity entity = response.getEntity(); StatusLine statusLine = response.getStatusLine(); switch (statusLine.getStatusCode()) { case HttpStatus.SC_OK: SAXBuilder builder = new SAXBuilder(); return builder.build(entity.getContent()); case HttpStatus.SC_UNAUTHORIZED: throw new MCRDatacenterAuthenticationException(); case HttpStatus.SC_NO_CONTENT: throw new MCRIdentifierUnresolvableException(doi.asString(), "The identifier " + doi.asString() + " is currently not resolvable"); case HttpStatus.SC_NOT_FOUND: throw new MCRIdentifierUnresolvableException(doi.asString(), "The identifier " + doi.asString() + " was not found!"); case HttpStatus.SC_GONE: throw new MCRIdentifierUnresolvableException(doi.asString(), "The identifier " + doi.asString() + " was deleted!"); default: throw new MCRDatacenterException("Unknown return status: " + getStatusString(response)); } } catch (IOException e) { throw new MCRDatacenterException("Error while resolving metadata!", e); } }
Example 17
Source File: RenRenResponseHandler.java From YiBo with Apache License 2.0 | 4 votes |
public String handleResponse(final HttpResponse response) throws HttpResponseException, IOException { StatusLine statusLine = response.getStatusLine(); HttpEntity entity = response.getEntity(); String responseString = (entity == null ? null : EntityUtils.toString(entity)); Logger.debug("RenRenResponseHandler : {}", responseString); if (responseString != null && responseString.contains("error_code") && responseString.startsWith("{")) { try { JSONObject json = new JSONObject(responseString); if (json.has("error_code")) { // 明确是异常响应,而不是包含了error_code的文本 int errorCode = json.getInt("error_code"); String errorDesc = json.getString("error_msg"); String requestPath = ""; if (json.has("request_args")) { JSONArray jsonArray = json.getJSONArray("request_args"); JSONObject jsonTmp = null; int size = jsonArray.length(); for (int i = 0; i < size; i++) { jsonTmp = jsonArray.getJSONObject(i); if ("method".equals(jsonTmp.getString("key"))) { requestPath = jsonTmp.getString("value"); break; } } } throw new LibRuntimeException( errorCode, requestPath, errorDesc, ServiceProvider.RenRen); } } catch (JSONException e) { throw new LibRuntimeException(LibResultCode.JSON_PARSE_ERROR, e, ServiceProvider.RenRen); } } int statusCode = statusLine.getStatusCode(); if (statusCode >= 300) { throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase()); } return responseString; }
Example 18
Source File: RestFidoActionsOnPolicy.java From fido2 with GNU Lesser General Public License v2.1 | 4 votes |
public static void patch(String REST_URI, String did, String accesskey, String secretkey, String sidpid, Long startdate, Long enddate, Integer version, String status, String notes, String policy) throws Exception { System.out.println("Patch policy test"); System.out.println("******************************************"); String apiversion = "2.0"; // Make API rest call and get response from the server String resourceLoc = REST_URI + Constants.REST_SUFFIX + did + Constants.PATCH_POLICY_ENDPOINT + "/" + sidpid; System.out.println("\nCalling update @ " + resourceLoc); PatchFidoPolicyRequest pfpr = new PatchFidoPolicyRequest(); pfpr.setStartDate(startdate); if (enddate != null) pfpr.setEndDate(enddate); pfpr.setVersion(version); pfpr.setStatus(status); pfpr.setNotes(notes); pfpr.setPolicy(policy); ObjectWriter ow = new ObjectMapper().writer(); String json = ow.writeValueAsString(pfpr); ContentType mimetype = ContentType.create("application/merge-patch+json"); StringEntity body = new StringEntity(json, mimetype); String currentDate = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z").format(new Date()); String contentSHA = common.calculateSha256(json); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPatch httpPatch = new HttpPatch(resourceLoc); httpPatch.setEntity(body); String requestToHmac = httpPatch.getMethod() + "\n" + contentSHA + "\n" + mimetype.getMimeType() + "\n" + currentDate + "\n" + apiversion + "\n" + httpPatch.getURI().getPath(); String hmac = common.calculateHMAC(secretkey, requestToHmac); httpPatch.addHeader("Authorization", "HMAC " + accesskey + ":" + hmac); httpPatch.addHeader("strongkey-content-sha256", contentSHA); httpPatch.addHeader("Content-Type", mimetype.getMimeType()); httpPatch.addHeader("Date", currentDate); httpPatch.addHeader("strongkey-api-version", apiversion); CloseableHttpResponse response = httpclient.execute(httpPatch); String result; try { StatusLine responseStatusLine = response.getStatusLine(); HttpEntity entity = response.getEntity(); result = EntityUtils.toString(entity); EntityUtils.consume(entity); switch (responseStatusLine.getStatusCode()) { case 200: break; case 401: System.out.println("Error during patch fido policy : 401 HMAC Authentication Failed"); return; case 404: System.out.println("Error during patch fido policy : 404 Resource not found"); return; case 400: case 500: default: System.out.println("Error during patch fido policy : " + responseStatusLine.getStatusCode() + " " + result); return; } } finally { response.close(); } System.out.println(" Response : " + result); System.out.println("\nPatch policy test complete."); System.out.println("******************************************"); }
Example 19
Source File: WebServiceNtlmSender.java From iaf with Apache License 2.0 | 4 votes |
@Override public Message sendMessage(Message message, IPipeLineSession session) throws SenderException, TimeOutException { String result = null; HttpPost httpPost = new HttpPost(getUrl()); try { StringEntity se = new StringEntity(message.asString()); httpPost.setEntity(se); if (StringUtils.isNotEmpty(getContentType())) { log.debug(getLogPrefix() + "setting Content-Type header [" + getContentType() + "]"); httpPost.addHeader("Content-Type", getContentType()); } if (StringUtils.isNotEmpty(getSoapAction())) { log.debug(getLogPrefix() + "setting SOAPAction header [" + getSoapAction() + "]"); httpPost.addHeader("SOAPAction", getSoapAction()); } log.debug(getLogPrefix() + "executing method"); HttpResponse httpresponse = httpClient.execute(httpPost); log.debug(getLogPrefix() + "executed method"); StatusLine statusLine = httpresponse.getStatusLine(); if (statusLine == null) { throw new SenderException(getLogPrefix() + "no statusline found"); } else { int statusCode = statusLine.getStatusCode(); String statusMessage = statusLine.getReasonPhrase(); if (statusCode == HttpServletResponse.SC_OK) { log.debug(getLogPrefix() + "status code [" + statusCode + "] message [" + statusMessage + "]"); } else { throw new SenderException(getLogPrefix() + "status code [" + statusCode + "] message [" + statusMessage + "]"); } } HttpEntity httpEntity = httpresponse.getEntity(); if (httpEntity == null) { log.warn(getLogPrefix() + "no response found"); } else { log.debug(getLogPrefix() + "response content length [" + httpEntity.getContentLength() + "]"); result = EntityUtils.toString(httpEntity); log.debug(getLogPrefix() + "retrieved result [" + result + "]"); } } catch (Exception e) { if (e instanceof SocketTimeoutException) { throw new TimeOutException(e); } if (e instanceof ConnectTimeoutException) { throw new TimeOutException(e); } throw new SenderException(e); } finally { httpPost.releaseConnection(); } return new Message(result); }
Example 20
Source File: DefaultCosHttpClient.java From cos-java-sdk-v5 with MIT License | 4 votes |
private <X extends CosServiceRequest> CosServiceException handlerErrorMessage( CosHttpRequest<X> request, HttpRequestBase httpRequestBase, final org.apache.http.HttpResponse apacheHttpResponse) throws IOException { final StatusLine statusLine = apacheHttpResponse.getStatusLine(); final int statusCode; final String reasonPhrase; if (statusLine == null) { statusCode = -1; reasonPhrase = null; } else { statusCode = statusLine.getStatusCode(); reasonPhrase = statusLine.getReasonPhrase(); } CosHttpResponse response = createResponse(httpRequestBase, request, apacheHttpResponse); CosServiceException exception = null; try { exception = errorResponseHandler.handle(response); log.debug("Received error response: " + exception); } catch (Exception e) { // If the errorResponseHandler doesn't work, then check for error // responses that don't have any content if (statusCode == 413) { exception = new CosServiceException("Request entity too large"); exception.setStatusCode(statusCode); exception.setErrorType(ErrorType.Client); exception.setErrorCode("Request entity too large"); } else if (statusCode == 503 && "Service Unavailable".equalsIgnoreCase(reasonPhrase)) { exception = new CosServiceException("Service unavailable"); exception.setStatusCode(statusCode); exception.setErrorType(ErrorType.Service); exception.setErrorCode("Service unavailable"); } else { String errorMessage = "Unable to unmarshall error response (" + e.getMessage() + "). Response Code: " + (statusLine == null ? "None" : statusCode) + ", Response Text: " + reasonPhrase; throw new CosClientException(errorMessage, e); } } exception.setStatusCode(statusCode); exception.fillInStackTrace(); return exception; }