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:com.mdmserver.mdb.ControllerQueue.java
private void sendGCMMessge(String cloudId, String jsonData) { try {/*from w w w .j ava 2 s . c o m*/ // Request.Post("http://android.googleapis.com/gcm/send").setHeader("Authorization", "key="+Config.gcmServerId) // .bodyString("{\"registration_ids\":[\""+cloudId+"\"],\"data\": {\"1\":\"2\",\"3\":\"4\"}}", ContentType.APPLICATION_JSON) // .execute().returnContent(); Logger.getLogger("Avin").log(Level.INFO, "{\"registration_ids\":[\"" + cloudId + "\"],\"data\":" + jsonData + "}"); Request.Post("http://android.googleapis.com/gcm/send") .setHeader("Authorization", "key=" + Config.gcmServerId) .bodyString("{\"registration_ids\":[\"" + cloudId + "\"],\"data\":" + jsonData + "}", ContentType.APPLICATION_JSON) .execute().returnContent(); System.out.println("Sending----------------------"); } catch (IOException ex) { Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex); } }
From source file:com.qwazr.graph.test.FullTest.java
@Test public void test000CreateDatabase() throws IOException { HashMap<String, PropertyTypeEnum> node_properties = new HashMap<String, PropertyTypeEnum>(); node_properties.put("type", PropertyTypeEnum.indexed); node_properties.put("date", PropertyTypeEnum.indexed); node_properties.put("name", PropertyTypeEnum.stored); node_properties.put("user", PropertyTypeEnum.stored); HashSet<String> edge_types = new HashSet<String>(); edge_types.add("see"); edge_types.add("buy"); GraphDefinition graphDef = new GraphDefinition(node_properties, edge_types); HttpResponse response = Request.Post(BASE_URL + '/' + TEST_BASE) .bodyString(JsonMapper.MAPPER.writeValueAsString(graphDef), ContentType.APPLICATION_JSON) .connectTimeout(60000).socketTimeout(60000).execute().returnResponse(); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); }
From source file:org.apache.gobblin.http.ApacheHttpRequestBuilderTest.java
/** * Build a {@link HttpUriRequest} from a {@link GenericRecord} *///from www . j a va 2s . c o m public void testBuildWriteRequest() throws IOException { String urlTemplate = "http://www.test.com/a/part1:${part1}/a/part2:${part2}"; String verb = "post"; ApacheHttpRequestBuilder builder = spy(new ApacheHttpRequestBuilder(urlTemplate, verb, "application/json")); ArgumentCaptor<RequestBuilder> requestBuilderArgument = ArgumentCaptor.forClass(RequestBuilder.class); Queue<BufferedRecord<GenericRecord>> queue = HttpTestUtils.createQueue(1, false); AsyncRequest<GenericRecord, HttpUriRequest> request = builder.buildRequest(queue); verify(builder).build(requestBuilderArgument.capture()); RequestBuilder expected = RequestBuilder.post(); expected.setUri("http://www.test.com/a/part1:01/a/part2:02?param1=01"); String payloadStr = "{\"id\":\"id0\"}"; expected.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType()) .setEntity(new StringEntity(payloadStr, ContentType.APPLICATION_JSON)); // Compare HttpUriRequest HttpTestUtils.assertEqual(requestBuilderArgument.getValue(), expected); Assert.assertEquals(request.getRecordCount(), 1); Assert.assertEquals(queue.size(), 0); }
From source file:org.apache.beam.sdk.io.elasticsearch.ElasticSearchIOTestUtils.java
/** * Synchronously deletes the target if it exists and then (re)creates it as a copy of source * synchronously.//from ww w. ja v a 2 s .c o m */ static void copyIndex(RestClient restClient, String source, String target) throws IOException { deleteIndex(restClient, target); HttpEntity entity = new NStringEntity( String.format("{\"source\" : { \"index\" : \"%s\" }, \"dest\" : { \"index\" : \"%s\" } }", source, target), ContentType.APPLICATION_JSON); restClient.performRequest("POST", "/_reindex", Collections.EMPTY_MAP, entity); }
From source file:org.apache.manifoldcf.agents.output.opensearchserver.OpenSearchServerScheduler.java
public OpenSearchServerScheduler(HttpClient client, OpenSearchServerConfig config, String schedulerName) throws ManifoldCFException { super(client, config); String path = StringUtils.replace(PATH, "{index_name}", URLEncoder.encode(config.getIndexName())); path = StringUtils.replace(path, "{scheduler_name}", URLEncoder.encode(schedulerName)); StringBuffer url = getApiUrlV2(path); HttpPut put = new HttpPut(url.toString()); put.setEntity(new StringEntity("{}", ContentType.APPLICATION_JSON)); call(put);//from www . ja v a 2 s.c o m }
From source file:com.joyent.manta.exception.MantaClientHttpResponseExceptionTest.java
private static HttpResponse responseWithErrorJson(final String json) { final StatusLine statusLine = new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_SERVICE_UNAVAILABLE, "UNAVAILABLE"); final HttpResponse response = mock(HttpResponse.class); when(response.getStatusLine()).thenReturn(statusLine); HttpEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON); when(response.getEntity()).thenReturn(entity); Header[] headers = new Header[] { new BasicHeader(HttpHeaders.DATE, "Wed, 13 Dec 2017 17:18:48 GMT"), new BasicHeader(HttpHeaders.SERVER, "Manta"), new BasicHeader(MantaHttpHeaders.REQUEST_ID, UUID.randomUUID().toString()), new BasicHeader("x-response-time", "198"), new BasicHeader(HttpHeaders.CONNECTION, "Keep-alive") }; when(response.getAllHeaders()).thenReturn(headers); return response; }
From source file:com.srotya.tau.ui.rules.TenantManager.java
public void createTenant(UserBean ub, Tenant tenant) throws Exception { if (tenant == null) { throw new NullPointerException("Tenant can't be empty"); }/*from w ww . j a v a2 s .c o m*/ try { Gson gson = new Gson(); CloseableHttpClient client = Utils.buildClient(am.getBaseUrl(), am.getConnectTimeout(), am.getRequestTimeout()); StringEntity entity = new StringEntity(gson.toJson(tenant), ContentType.APPLICATION_JSON); HttpPost post = new HttpPost(am.getBaseUrl() + TENANT_URL); post.setEntity(entity); if (am.isEnableAuth()) { post.addHeader(BapiLoginDAO.X_SUBJECT_TOKEN, ub.getToken()); post.addHeader(BapiLoginDAO.HMAC, ub.getHmac()); } CloseableHttpResponse resp = client.execute(post); if (!Utils.validateStatus(resp)) { throw new Exception("status code:" + resp.getStatusLine().getStatusCode()); } } catch (Exception e) { logger.log(Level.SEVERE, "Failed to create tenant:" + tenant + "\t" + e.getMessage()); throw e; } }
From source file:org.elasticsearch.smoketest.SmokeTestWatcherWithSecurityClientYamlTestSuiteIT.java
@Before public void startWatcher() throws Exception { // delete the watcher history to not clutter with entries from other test getAdminExecutionContext().callApi("indices.delete", Collections.singletonMap("index", ".watcher-history-*"), emptyList(), emptyMap()); // create one document in this index, so we can test in the YAML tests, that the index cannot be accessed Response resp = adminClient().performRequest("PUT", "/index_not_allowed_to_read/doc/1", Collections.emptyMap(), new StringEntity("{\"foo\":\"bar\"}", ContentType.APPLICATION_JSON)); assertThat(resp.getStatusLine().getStatusCode(), is(201)); assertBusy(() -> {/*from w w w . ja va 2 s . c o m*/ ClientYamlTestResponse response = getAdminExecutionContext().callApi("xpack.watcher.stats", emptyMap(), emptyList(), emptyMap()); String state = (String) response.evaluate("stats.0.watcher_state"); switch (state) { case "stopped": ClientYamlTestResponse startResponse = getAdminExecutionContext().callApi("xpack.watcher.start", emptyMap(), emptyList(), emptyMap()); boolean isAcknowledged = (boolean) startResponse.evaluate("acknowledged"); assertThat(isAcknowledged, is(true)); break; case "stopping": throw new AssertionError("waiting until stopping state reached stopped state to start again"); case "starting": throw new AssertionError("waiting until starting state reached started state"); case "started": // all good here, we are done break; default: throw new AssertionError("unknown state[" + state + "]"); } }); assertBusy(() -> { for (String template : WatcherIndexTemplateRegistryField.TEMPLATE_NAMES) { ClientYamlTestResponse templateExistsResponse = getAdminExecutionContext().callApi( "indices.exists_template", singletonMap("name", template), emptyList(), emptyMap()); assertThat(templateExistsResponse.getStatusCode(), is(200)); } }); }
From source file:org.jboss.pnc.causewayclient.DefaultCausewayClient.java
boolean post(String url, String jsonMessage, String authToken) { Header authHeader = new BasicHeader("Authorization", "Bearer " + authToken); HttpResponse response;//from w w w. j a va 2 s . c o m try { logger.info("Making POST request to {}.", url); if (logger.isDebugEnabled()) logger.debug("Request body {}.", secureBodyLog(jsonMessage)); response = Request.Post(url).addHeader(authHeader).bodyString(jsonMessage, ContentType.APPLICATION_JSON) .execute().returnResponse(); } catch (IOException e) { logger.error("Failed to invoke remote Causeway.", e); return false; } try { int statusCode = response.getStatusLine().getStatusCode(); logger.info("Response status: {}", statusCode); logger.debug("Response: " + EntityUtils.toString(response.getEntity())); if (!HttpUtils.isSuccess(statusCode)) { return false; } } catch (IOException e) { logger.error("Failed to read Causeway response.", e); return false; } return true; }