List of usage examples for org.apache.http.client HttpResponseException HttpResponseException
public HttpResponseException(final int statusCode, final String s)
From source file:com.example.pierre.applicompanies.library_http.BinaryHttpResponseHandler.java
@Override public final void sendResponseMessage(HttpResponse response) throws IOException { StatusLine status = response.getStatusLine(); Header[] contentTypeHeaders = response.getHeaders(AsyncHttpClient.HEADER_CONTENT_TYPE); if (contentTypeHeaders.length != 1) { //malformed/ambiguous HTTP Header, ABORT! sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null, new HttpResponseException( status.getStatusCode(), "None, or more than one, Content-Type Header found!")); return;//from w w w. j a va2 s. c o m } Header contentTypeHeader = contentTypeHeaders[0]; boolean foundAllowedContentType = false; for (String anAllowedContentType : getAllowedContentTypes()) { try { if (Pattern.matches(anAllowedContentType, contentTypeHeader.getValue())) { foundAllowedContentType = true; } } catch (PatternSyntaxException e) { Log.e("BinaryHttpResponseHandler", "Given pattern is not valid: " + anAllowedContentType, e); } } if (!foundAllowedContentType) { //Content-Type not in allowed list, ABORT! sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null, new HttpResponseException( status.getStatusCode(), "Content-Type (" + contentTypeHeader.getValue() + ") not allowed!")); return; } super.sendResponseMessage(response); }
From source file:com.puppetlabs.puppetdb.javaclient.impl.JSonResponseHandler.java
@Override public V handleResponse(HttpResponse response) throws IOException { StatusLine statusLine = response.getStatusLine(); int code = statusLine.getStatusCode(); if (code >= 300) { String msg;//from w w w . j av a 2 s . c o m try { msg = EntityUtils.toString(response.getEntity()); if (msg == null) msg = statusLine.getReasonPhrase(); else { msg = statusLine.getReasonPhrase() + ": " + msg; } } catch (Exception e) { // Just skip msg = statusLine.getReasonPhrase(); } throw new HttpResponseException(statusLine.getStatusCode(), msg); } HttpEntity entity = response.getEntity(); if (isOk(code)) { if (type == null) return null; return parseJson(getStream(entity), type); } throw createException(getStream(entity), code, statusLine.getReasonPhrase()); }
From source file:org.kontalk.xmppserver.registration.checkmobi.CheckmobiValidationClient.java
public VerifyResult verify(String requestId, String pin) throws IOException { try {//w ww.j av a 2s . c om JsonObject data = _verify(requestId, pin); try { boolean validated = data.getAsJsonPrimitive("validated").getAsBoolean(); return new VerifyResult(validated); } catch (NullPointerException e) { // simulate bad request throw new HttpResponseException(400, "Bad request"); } } catch (HttpResponseException e) { return new VerifyResult(e); } }
From source file:com.lfrj.diancan.http.BinaryHttpResponseHandler.java
@Override public final void sendResponseMessage(HttpResponse response) throws IOException { StatusLine status = response.getStatusLine(); Header[] contentTypeHeaders = response.getHeaders(AsyncHttpClient.HEADER_CONTENT_TYPE); if (contentTypeHeaders.length != 1) { // malformed/ambiguous HTTP Header, ABORT! sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null, new HttpResponseException( status.getStatusCode(), "None, or more than one, Content-Type Header found!")); return;/*from w w w . j a v a 2s. co m*/ } Header contentTypeHeader = contentTypeHeaders[0]; boolean foundAllowedContentType = false; for (String anAllowedContentType : getAllowedContentTypes()) { try { if (Pattern.matches(anAllowedContentType, contentTypeHeader.getValue())) { foundAllowedContentType = true; } } catch (PatternSyntaxException e) { Log.e("BinaryHttpResponseHandler", "Given pattern is not valid: " + anAllowedContentType, e); } } if (!foundAllowedContentType) { // Content-Type not in allowed list, ABORT! sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null, new HttpResponseException(status.getStatusCode(), "Content-Type not allowed!")); return; } super.sendResponseMessage(response); }
From source file:com.amytech.android.library.utils.asynchttp.BinaryHttpResponseHandler.java
@Override public final void sendResponseMessage(HttpResponse response) throws IOException { StatusLine status = response.getStatusLine(); Header[] contentTypeHeaders = response.getHeaders(AsyncHttpClient.HEADER_CONTENT_TYPE); if (contentTypeHeaders.length != 1) { // malformed/ambiguous HTTP Header, ABORT! sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null, new HttpResponseException( status.getStatusCode(), "None, or more than one, Content-Type Header found!")); return;/* www.ja v a 2s . c o m*/ } Header contentTypeHeader = contentTypeHeaders[0]; boolean foundAllowedContentType = false; for (String anAllowedContentType : getAllowedContentTypes()) { try { if (Pattern.matches(anAllowedContentType, contentTypeHeader.getValue())) { foundAllowedContentType = true; } } catch (PatternSyntaxException e) { Log.e("BinaryHttpResponseHandler", "Given pattern is not valid: " + anAllowedContentType, e); } } if (!foundAllowedContentType) { // Content-Type not in allowed list, ABORT! sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null, new HttpResponseException( status.getStatusCode(), "Content-Type (" + contentTypeHeader.getValue() + ") not allowed!")); return; } super.sendResponseMessage(response); }
From source file:com.jaspersoft.studio.server.protocol.restv2.RESTv2ExceptionHandler.java
protected void handleErrorDescriptor(Response res, IProgressMonitor monitor, int status) throws HttpResponseException { res.bufferEntity();/*from www . j av a2s. c o m*/ try { ErrorDescriptor ed = res.readEntity(ErrorDescriptor.class); String msg = ed.getErrorCode() + "\n" + buildMessage(monitor, "", ed); if (!ed.getErrorCode().contains("{0}") && ed.getParameters() != null) for (String str : ed.getParameters()) msg += "\n" + str; throw new HttpResponseException(status, msg); } catch (Throwable e) { if (e instanceof HttpResponseException) throw (HttpResponseException) e; else if (status == 400) handleErrorDescriptorList(res, monitor, status); else throw new RuntimeException(e); } }
From source file:com.vaguehope.onosendai.util.HttpHelper.java
private static <R> R fetchWithFollowRedirects(final Method method, final URL url, final HttpStreamHandler<R> streamHandler, final int redirectCount) throws IOException, URISyntaxException { final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); try {/*from ww w .j a va 2s .c om*/ connection.setRequestMethod(method.toString()); connection.setInstanceFollowRedirects(false); connection.setConnectTimeout((int) TimeUnit.SECONDS.toMillis(HTTP_CONNECT_TIMEOUT_SECONDS)); connection.setReadTimeout((int) TimeUnit.SECONDS.toMillis(HTTP_READ_TIMEOUT_SECONDS)); connection.setRequestProperty("User-Agent", "curl/1"); // Make it really clear this is not a browser. //connection.setRequestProperty("Accept-Encoding", "identity"); This fixes missing Content-Length headers but feels wrong. connection.connect(); InputStream is = null; try { final int responseCode = connection.getResponseCode(); // For some reason some devices do not follow redirects. :( if (responseCode == 301 || responseCode == 302 || responseCode == 303 || responseCode == 307) { // NOSONAR not magic numbers. Its HTTP spec. if (redirectCount >= MAX_REDIRECTS) throw new TooManyRedirectsException(responseCode, url, MAX_REDIRECTS); final String locationHeader = connection.getHeaderField("Location"); if (locationHeader == null) throw new HttpResponseException(responseCode, "Location header missing. Headers present: " + connection.getHeaderFields() + "."); connection.disconnect(); final URL locationUrl; if (locationHeader.toLowerCase(Locale.ENGLISH).startsWith("http")) { locationUrl = new URL(locationHeader); } else { locationUrl = url.toURI().resolve(locationHeader).toURL(); } return fetchWithFollowRedirects(method, locationUrl, streamHandler, redirectCount + 1); } if (responseCode < 200 || responseCode >= 300) { // NOSONAR not magic numbers. Its HTTP spec. throw new NotOkResponseException(responseCode, connection, url); } is = connection.getInputStream(); final int contentLength = connection.getContentLength(); if (contentLength < 1) LOG.w("Content-Length=%s for %s.", contentLength, url); return streamHandler.handleStream(connection, is, contentLength); } finally { IoHelper.closeQuietly(is); } } finally { connection.disconnect(); } }
From source file:fm.last.musicbrainz.coverart.impl.DefaultCoverArtArchiveClientTest.java
@Test(expected = IOException.class) public void nonExistantImageThrowsIoException() throws Exception { doThrow(new HttpResponseException(HttpStatus.SC_NOT_FOUND, "")).when(httpClient).execute(any(HttpGet.class), eq(FetchImageDataResponseHandler.INSTANCE)); client.getImageData("doesnotexist.jpg"); }
From source file:org.neo4j.ogm.session.transaction.TransactionManager.java
private HttpResponse executeRequest(HttpRequestBase request) { try {//from ww w . j a va2s .com request.setHeader(new BasicHeader("Accept", "application/json;charset=UTF-8")); HttpRequestAuthorization.authorize(request, credentials); HttpResponse response = httpClient.execute(request); StatusLine statusLine = response.getStatusLine(); logger.debug("Status code: {}", statusLine.getStatusCode()); if (statusLine.getStatusCode() >= 300) { throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase()); } HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { String responseText = EntityUtils.toString(responseEntity); logger.debug(responseText); EntityUtils.consume(responseEntity); if (responseText.contains("\"errors\":[{") || responseText.contains("\"errors\": [{")) { throw new ErrorsException(responseText); } } return response; } catch (Exception e) { throw new ResultProcessingException("Failed to execute request: ", e); } // always clean up the connection and the thread-local transaction instance; finally { request.releaseConnection(); transaction.remove(); } }