List of usage examples for org.apache.http.entity ContentType APPLICATION_JSON
ContentType APPLICATION_JSON
To view the source code for org.apache.http.entity ContentType APPLICATION_JSON.
Click Source Link
From source file:org.ulyssis.ipp.publisher.HttpOutput.java
@Override public void outputScore(Score score) { SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(createSslCustomContext(), new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); try (CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build()) { HttpPost req = new HttpPost(options.getHttp().toURI()); byte[] scoreBytes = Serialization.getJsonMapper().writeValueAsBytes(score); HttpEntity ent = new ByteArrayEntity(scoreBytes, ContentType.APPLICATION_JSON); req.setEntity(ent);//from ww w. j av a 2 s.c o m try (CloseableHttpResponse response = httpClient.execute(req)) { if (response.getStatusLine().getStatusCode() != 200) { LOG.error("Non-success result!"); return; } HttpEntity entity = response.getEntity(); if (entity.getContentLength() != 7L) { LOG.error("Non-success result!"); return; } String result = EntityUtils.toString(entity, StandardCharsets.UTF_8); if (!"SUCCESS".equals(result)) { LOG.error("Non-success result!"); return; } } } catch (Exception e) { // TODO: DO SOMETHING WITH THE EXCEPTION! LOG.error("Exception", e); } }
From source file:org.hawkular.component.pinger.MetricPublisher.java
/** * Serializes the given {@link PingStatus} and then submits it to Hawkular-metrics service via REST * * @param status//from ww w . ja va2s . c o m * the {@link PingStatus} to publish */ @Asynchronous public void sendToMetricsViaRest(PingStatus status) { List<Map<String, Object>> mMetrics = new ArrayList<>(); final PingDestination dest = status.getDestination(); final String resourceId = dest.getResourceId(); final long timestamp = status.getTimestamp(); addDataItem(mMetrics, resourceId, timestamp, status.getDuration(), "duration"); addDataItem(mMetrics, resourceId, timestamp, status.getCode(), "code"); // Send it to metrics via rest String payload = new Gson().toJson(mMetrics); HttpClient client = HttpClientBuilder.create().build(); HttpPost request = new HttpPost(configuration.getMetricsBaseUri() + "/gauges/data"); request.addHeader("Hawkular-Tenant", status.getDestination().getTenantId()); request.setEntity(new StringEntity(payload, ContentType.APPLICATION_JSON)); try { HttpResponse response = client.execute(request); if (response.getStatusLine().getStatusCode() > 399) { Log.LOG.wMetricPostStatus(response.getStatusLine().toString()); } } catch (IOException e) { Log.LOG.eMetricsIoException(e); } }
From source file:org.elasticsearch.client.HeapBufferedAsyncResponseConsumerTests.java
private static void bufferLimitTest(HeapBufferedAsyncResponseConsumer consumer, int bufferLimit) throws Exception { ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); StatusLine statusLine = new BasicStatusLine(protocolVersion, 200, "OK"); consumer.onResponseReceived(new BasicHttpResponse(statusLine)); final AtomicReference<Long> contentLength = new AtomicReference<>(); HttpEntity entity = new StringEntity("", ContentType.APPLICATION_JSON) { @Override//from w w w .j a v a 2 s . co m public long getContentLength() { return contentLength.get(); } }; contentLength.set(randomLong(bufferLimit)); consumer.onEntityEnclosed(entity, ContentType.APPLICATION_JSON); contentLength.set(randomLongBetween(bufferLimit + 1, MAX_TEST_BUFFER_SIZE)); try { consumer.onEntityEnclosed(entity, ContentType.APPLICATION_JSON); } catch (ContentTooLongException e) { assertEquals("entity content is too long [" + entity.getContentLength() + "] for the configured buffer limit [" + bufferLimit + "]", e.getMessage()); } }
From source file:org.kiji.bento.box.UpgradeServerClient.java
/** * Sends a check-in message to the upgrade server and receives a response. * * @param checkinMessage to send to the upgrade server. * @return the response sent by the server. * @throws IOException if there is a problem making the http request, consuming the response * to the request, or if the upgrade server responded with an error. */// w w w . ja va 2s.c o m public UpgradeResponse checkin(UpgradeCheckin checkinMessage) throws IOException { // Create a POST request to send to the update server. HttpPost postRequest = new HttpPost(mCheckinServerURI); // Create an Entity for the message body with the proper content type and content taken // from the provided checkin message. HttpEntity postRequestEntity = new StringEntity(checkinMessage.toJSON(), ContentType.APPLICATION_JSON); postRequest.setEntity(postRequestEntity); // Execute the request. HttpResponse response = mHttpClient.execute(postRequest); try { HttpEntity responseEntity = response.getEntity(); String responseBody = EntityUtils.toString(responseEntity); // The response body should contain JSON that can be used to create an upgrade response. return UpgradeResponse.fromJSON(responseBody); } finally { postRequest.releaseConnection(); } }
From source file:se.curity.examples.oauth.jwt.JwkManager.java
protected String fetchKeys() throws IOException { HttpGet get = new HttpGet(_jwksUri); get.setHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.getMimeType()); HttpResponse response = _httpClient.execute(get); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { _logger.error("Got error from Jwks server: " + response.getStatusLine().getStatusCode()); throw new IOException("Got error from Jwks server: " + response.getStatusLine().getStatusCode()); }//w w w.j a va 2 s . c o m return EntityUtils.toString(response.getEntity(), Charsets.UTF_8); }
From source file:de.micromata.logging.log4j.appender.elasticsearch.ElasticsearchConnection.java
@Override public void insertObject(NoSQLObject<Map<String, Object>> object) { final String indexName = indexName(); if (config.isRestful()) { String url = String.format("%s/%s/%s", config.getHttpEndpoint(), indexName, config.getTypeName()); HttpPost httpPost = new HttpPost(url); String json = new Gson().toJson(object.unwrap()); httpPost.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON)); HttpClient httpClient = HttpClients.createDefault(); try {/* w w w. j av a 2 s . c om*/ HttpResponse execute = httpClient.execute(httpPost); if (execute.getStatusLine().getStatusCode() != 201) { logger.error("Failed to write log event to Elasticsearch ({}): {}", url, execute); } } catch (IOException e) { logger.error("Failed to write log event to Elasticsearch ({}) due to error: ", e, url); } } else { try { IndexResponse indexResponse = client.prepareIndex(indexName, config.getTypeName()) .setSource(object.unwrap()).execute().get(); if (indexResponse.isCreated() == false) { throw new AppenderLoggingException( "Failed to write log event to Elasticsearch: " + indexResponse.getHeaders()); } } catch (InterruptedException e) { logger.error("Failed to write log event to Elasticsearch due to error: ", e); } catch (ExecutionException e) { logger.error("Failed to write log event to Elasticsearch due to error: ", e); } } }
From source file:com.vmware.photon.controller.nsxclient.RestClientTest.java
@Test public void testPerformPut() { String payload = "{name: DUMMY}"; ArgumentCaptor<HttpUriRequest> argumentCaptor = setup(RestClient.Method.PUT, new StringEntity(payload, ContentType.APPLICATION_JSON)); HttpUriRequest request = argumentCaptor.getValue(); assertNotNull(request);/* ww w .j a va2 s. co m*/ assertTrue(request.getMethod().equalsIgnoreCase(RestClient.Method.PUT.toString())); assertEquals(request.getURI().toString(), target + path); HttpEntityEnclosingRequest httpEntityEnclosingRequest = (HttpEntityEnclosingRequest) request; String actualPayload = null; try { actualPayload = IOUtils.toString(httpEntityEnclosingRequest.getEntity().getContent()); } catch (IOException e) { fail(e.getMessage()); } assertEquals(actualPayload, payload); }
From source file:com.appdirect.sdk.feature.CanValidateCustomerDataIntegrationTest.java
@Test public void validateSubscription() throws Exception { Map<String, String> dataMap = new HashMap<>(); dataMap.put("subscriptionId", "76547391"); dataMap.put("sku", "Google-Apps-For-Business"); String jsonData = objectMapper.writeValueAsString(dataMap); HttpResponse response = fakeAppmarket.sendSignedPostRequestTo( baseConnectorUrl() + SUBSCRIPTION_API_END_POINT, new StringEntity(jsonData, ContentType.APPLICATION_JSON)); assertThat(response.getStatusLine().getStatusCode()).isEqualTo(HttpStatus.SC_OK); Map<String, Object> result = objectMapper.readValue(response.getEntity().getContent(), HashMap.class); assertThat(result.size()).isEqualTo(3); assertThat(result.get("errorCode")).isEqualTo("CONFIGURATION_ERROR"); assertThat(result.get("message")).isEqualTo("Subscription validation is not supported."); assertThat(result.get("success")).isEqualTo(false); }
From source file:com.enitalk.controllers.youtube.BotAware.java
public void sendLastCommand(JsonNode dest) throws ExecutionException, IOException { HttpPost post = new HttpPost(env.getProperty("bot.sendLast")); String auth = botAuth();// www . ja va2 s . c o m post.addHeader("Authorization", "Bearer " + auth); post.setEntity(new StringEntity(dest.toString(), ContentType.APPLICATION_JSON)); CloseableHttpResponse resp = client.execute(post); IOUtils.closeQuietly(resp); }