List of usage examples for org.apache.http.client ResponseHandler ResponseHandler
ResponseHandler
From source file:com.codspire.mojo.artifactlookup.ProcessResponse.java
/** * /*from ww w . j av a 2 s. c om*/ * @param sha1Checksum * @return */ public GAV lookupRepo(String sha1Checksum) { String url = apiEndpoint + sha1Checksum; log.debug("Request URL: " + url); HttpGet httpGet = new HttpGet(url); 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 = null; GAV gav; try (CloseableHttpClient httpclient = HttpClients.createDefault()) { responseBody = httpclient.execute(httpGet, responseHandler); if (log.isDebugEnabled()) { log.debug("----------------------------------------"); log.debug(responseBody); log.debug("----------------------------------------"); } gav = getGAV(responseBody); if (log.isDebugEnabled()) { log.debug(gav.toString()); } } catch (Exception e) { throw new ContextedRuntimeException("Unable to get the http response: " + url, e); } if (gav == null || gav.isIncomlete()) { throw new ContextedRuntimeException("No GAV found for " + sha1Checksum); } return gav; }
From source file:org.ldp4j.server.IntegrationTestHelper.java
public String httpRequest(final HttpUriRequest request) throws Exception { final AtomicReference<String> body = new AtomicReference<String>(); ResponseHandler<String> responseHandler = new ResponseHandler<String>() { public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException { String responseBody = logResponse(response); // TODO: Add validation mechanism here body.set(responseBody);/*from www. j a v a 2 s . c om*/ return responseBody; } private final String NL = System.getProperty("line.separator"); private String logResponse(final HttpResponse response) throws IOException { HttpEntity entity = response.getEntity(); String responseBody = entity != null ? EntityUtils.toString(entity) : null; if (logger.isDebugEnabled()) { StringBuilder builder = new StringBuilder(); builder.append("-- REQUEST COMPLETED -------------------------").append(NL); builder.append("-- RESPONSE INIT -----------------------------").append(NL); builder.append(response.getStatusLine().toString()).append(NL); builder.append("-- RESPONSE HEADERS---------------------------").append(NL); for (org.apache.http.Header h : response.getAllHeaders()) { builder.append(h.getName() + " : " + h.getValue()).append(NL); } if (responseBody != null && responseBody.length() > 0) { builder.append("-- RESPONSE BODY -----------------------------").append(NL); builder.append(responseBody).append(NL); } builder.append("-- RESPONSE END ------------------------------"); logger.debug(builder.toString()); } return responseBody; } }; logger.debug("-- REQUEST INIT -------------------------------"); logger.debug(request.getRequestLine().toString()); httpclient.execute(request, responseHandler); return body.get(); }
From source file:eu.esdihumboldt.hale.io.geoserver.rest.AbstractResourceManager.java
/** * @see eu.esdihumboldt.hale.io.geoserver.rest.ResourceManager#exists() *//*w w w. j a va 2 s.c om*/ @Override public boolean exists() { checkResourceSet(); try { return executor.execute(Request.Get(getResourceURL())).handleResponse(new ResponseHandler<Boolean>() { /** * @see org.apache.http.client.ResponseHandler#handleResponse(org.apache.http.HttpResponse) */ @Override public Boolean handleResponse(HttpResponse response) throws ClientProtocolException, IOException { int statusCode = response.getStatusLine().getStatusCode(); String reason = response.getStatusLine().getReasonPhrase(); switch (statusCode) { case 200: return true; case 404: return false; default: throw new HttpResponseException(statusCode, reason); } } }); } catch (Exception e) { throw new ResourceException(e); } }
From source file:it.anyplace.sync.discovery.protocol.gd.GlobalDiscoveryHandler.java
/** * /* w ww. j av a 2s . c o m*/ * @param server * @param deviceId * @return null on error, empty list on 'not found', address list otherwise */ private @Nullable List<DeviceAddress> doQuery(String server, final String deviceId) { try { logger.trace("querying server {} for device id {}", server, deviceId); HttpClient httpClient = HttpClients.custom() .setSSLSocketFactory(new SSLConnectionSocketFactory( new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)) .build(); HttpGet httpGet = new HttpGet("https://" + server + "/v2/?device=" + deviceId); return httpClient.execute(httpGet, new ResponseHandler<List<DeviceAddress>>() { @Override public List<DeviceAddress> handleResponse(HttpResponse response) throws ClientProtocolException, IOException { switch (response.getStatusLine().getStatusCode()) { case HttpStatus.SC_NOT_FOUND: logger.debug("device not found: {}", deviceId); return Collections.<DeviceAddress>emptyList(); case HttpStatus.SC_OK: AnnouncementMessageBean announcementMessageBean = gson.fromJson( EntityUtils.toString(response.getEntity()), AnnouncementMessageBean.class); List<DeviceAddress> list = Lists .newArrayList(Iterables.transform( firstNonNull(announcementMessageBean.getAddresses(), Collections.<String>emptyList()), new Function<String, DeviceAddress>() { @Override public DeviceAddress apply(String address) { return new DeviceAddress(deviceId, address); } })); logger.debug("found address list = {}", list); return list; default: throw new IOException("http error " + response.getStatusLine()); } } }); } catch (Exception ex) { logger.warn("error in global discovery for device = " + deviceId, ex); } return null; }
From source file:edu.tum.cs.ias.knowrob.BarcodeWebLookup.java
public static String lookUpEANsearch(String ean) { String res = ""; if (ean != null && ean.length() > 0) { HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); //httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-16"); try {/*from w w w . jav a 2s . com*/ HttpGet httpget = new HttpGet("http://www.ean-search.org/perl/ean-search.pl?ean=" + ean + "&os=1"); httpget.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8"); httpget.getParams().setParameter(CoreProtocolPNames.HTTP_ELEMENT_CHARSET, "ASCII"); System.out.println(httpget.getURI()); // Create a response handler ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() { public byte[] handleResponse(HttpResponse response) throws ClientProtocolException, IOException { HttpEntity entity = response.getEntity(); if (entity != null) { return EntityUtils.toByteArray(entity); } else { return null; } } }; byte[] response = httpclient.execute(httpget, handler); // String responseBody = httpclient.execute(httpget, handler); // new HeapByteBuffer(responseBody.getBytes(), 0, responseBody.getBytes().length)); // // Charset a = Charset.forName("UTF-8"); // a.newEncoder().encode(responseBody.getBytes()); // // System.out.println(responseBody); // Parse response document res = response.toString(); } catch (UnsupportedEncodingException uee) { uee.printStackTrace(); } catch (ClientProtocolException cpe) { cpe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } finally { if (httpclient != null) { httpclient.getConnectionManager().shutdown(); } } } return res; }
From source file:com.networknt.client.ClientTest.java
public String callApiSync() throws Exception { String url = "http://localhost:8887/api"; CloseableHttpClient client = Client.getInstance().getSyncClient(); HttpGet httpGet = new HttpGet(url); ResponseHandler<String> responseHandler = new ResponseHandler<String>() { @Override/* ww w . j a v a2 s.com*/ public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException { int status = response.getStatusLine().getStatusCode(); Assert.assertEquals(200, status); 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 = null; try { Client.getInstance().addAuthorizationWithScopeToken(httpGet, "Bearer token"); responseBody = client.execute(httpGet, responseHandler); Assert.assertEquals("{\"message\":\"OK!\"}", responseBody); logger.debug("message = " + responseBody); } catch (Exception e) { e.printStackTrace(); responseBody = "{\"message\":\"Error!\"}"; } return responseBody; }
From source file:com.github.rnewson.couchdb.lucene.rhino.RhinoDocument.java
private void addAttachment(final RhinoAttachment attachment, final String id, final Database database, final Document out) throws IOException { final ResponseHandler<Void> handler = new ResponseHandler<Void>() { public Void handleResponse(final HttpResponse response) throws ClientProtocolException, IOException { final HttpEntity entity = response.getEntity(); try { Tika.INSTANCE.parse(entity.getContent(), entity.getContentType().getValue(), attachment.fieldName, out); } finally { entity.consumeContent(); }/*from ww w . j ava2 s .c o m*/ return null; } }; database.handleAttachment(id, attachment.attachmentName, handler); }
From source file:org.callimachusproject.client.HttpClientFactoryTest.java
@Test public void test200() throws Exception { responses.add(new BasicHttpResponse(_200)); client.execute(new HttpGet("http://example.com/200"), new ResponseHandler<Void>() { public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException { assertEquals(_200.getStatusCode(), response.getStatusLine().getStatusCode()); return null; }/* w w w . ja v a 2 s.c om*/ }); }
From source file:org.apache.marmotta.client.clients.ImportClient.java
/** * Upload/Import a dataset in the Marmotta Server. The dataset is given as an Inputstream that contains data of the * mime type passed as argument. The mime type must be one of the acceptable types of the server. * * @param in InputStream to read the dataset from; will be consumed by this method * @param mimeType mime type of the input data * @throws IOException// w w w. j av a 2 s .c om * @throws MarmottaClientException */ public void uploadDataset(final InputStream in, final String mimeType) throws IOException, MarmottaClientException { //Preconditions.checkArgument(acceptableTypes.contains(mimeType)); HttpClient httpClient = HTTPUtil.createClient(config); HttpPost post = HTTPUtil.createPost(URL_UPLOAD_SERVICE, config); post.setHeader("Content-Type", mimeType); ContentProducer cp = new ContentProducer() { @Override public void writeTo(OutputStream outstream) throws IOException { ByteStreams.copy(in, outstream); } }; post.setEntity(new EntityTemplate(cp)); ResponseHandler<Boolean> handler = new ResponseHandler<Boolean>() { @Override public Boolean handleResponse(HttpResponse response) throws ClientProtocolException, IOException { EntityUtils.consume(response.getEntity()); switch (response.getStatusLine().getStatusCode()) { case 200: log.debug("dataset uploaded updated successfully"); return true; case 412: log.error("mime type {} not acceptable by import service", mimeType); return false; default: log.error("error uploading dataset: {} {}", new Object[] { response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase() }); return false; } } }; try { httpClient.execute(post, handler); } catch (IOException ex) { post.abort(); throw ex; } finally { post.releaseConnection(); } }
From source file:org.cloudsmith.geppetto.forge.client.ForgeHttpClient.java
@Override public void download(String urlStr, Map<String, String> params, final OutputStream output) throws IOException { HttpGet request = createGetRequest(urlStr, params, false); configureRequest(request);// ww w.jav a 2 s . com httpClient.execute(request, new ResponseHandler<Void>() { @Override public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException { StatusLine statusLine = response.getStatusLine(); int code = statusLine.getStatusCode(); if (code != HttpStatus.SC_OK) throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase()); HttpEntity entity = response.getEntity(); entity.writeTo(output); return null; } }); }