Example usage for org.apache.http.entity ContentType APPLICATION_JSON

List of usage examples for org.apache.http.entity ContentType APPLICATION_JSON

Introduction

In this page you can find the example usage for org.apache.http.entity ContentType APPLICATION_JSON.

Prototype

ContentType APPLICATION_JSON

To view the source code for org.apache.http.entity ContentType APPLICATION_JSON.

Click Source Link

Usage

From source file:de.devbliss.apitester.factory.impl.EntityBuilder.java

/**
 * Builds an entity from a given raw payload. If the payload is a string, it is directly used as payload, and the
 * entity's content type is text/plain, otherwise, it is serialized to JSON and the content type is set to
 * application/json./*from   www.j a v  a2 s  .  c  o  m*/
 * 
 * @param payload payload which must not be null
 * @return entity
 * @throws IOException
 */
public StringEntity buildEntity(Object payload) throws IOException {
    boolean payloadIsString = payload instanceof String;
    String payloadAsString;

    if (payloadIsString) {
        payloadAsString = (String) payload;
    } else {
        payloadAsString = gson.toJson(payload);
    }

    StringEntity entity = new StringEntity(payloadAsString, ENCODING);

    if (payloadIsString) {
        entity.setContentType(ContentType.TEXT_PLAIN.getMimeType());
    } else {
        entity.setContentType(ContentType.APPLICATION_JSON.getMimeType());
    }

    return entity;
}

From source file:io.gravitee.gateway.standalone.PostContentGatewayTest.java

@Test
public void call_post_content() throws Exception {
    InputStream is = this.getClass().getClassLoader().getResourceAsStream("case1/request_content.json");
    String content = StringUtils.copy(is);

    Request request = Request.Post("http://localhost:8082/test/my_team").bodyString(content,
            ContentType.APPLICATION_JSON);

    Response response = request.execute();

    HttpResponse returnResponse = response.returnResponse();
    assertEquals(HttpStatus.SC_OK, returnResponse.getStatusLine().getStatusCode());

    String responseContent = StringUtils.copy(returnResponse.getEntity().getContent());
    assertEquals(content, responseContent);
}

From source file:org.elasticsearch.smoketest.MonitoringWithWatcherRestIT.java

@After
public void cleanExporters() throws Exception {
    String body = Strings.toString(jsonBuilder().startObject().startObject("transient")
            .nullField("xpack.monitoring.exporters.*").endObject().endObject());
    assertOK(adminClient().performRequest("PUT", "_cluster/settings", Collections.emptyMap(),
            new StringEntity(body, ContentType.APPLICATION_JSON)));

    assertOK(adminClient().performRequest("DELETE", ".watch*", Collections.emptyMap()));
}

From source file:com.threatconnect.sdk.conn.HttpRequestExecutor.java

private void applyEntityAsJSON(HttpRequestBase httpBase, Object obj) throws JsonProcessingException {
    String jsonData = StringUtil.toJSON(obj);
    logger.trace("entity : " + jsonData);
    ((HttpEntityEnclosingRequestBase) httpBase)
            .setEntity(new StringEntity(jsonData, ContentType.APPLICATION_JSON));
}

From source file:com.enitalk.controllers.youtube.BotAware.java

public void sendTag(ObjectNode dest) throws IOException, ExecutionException {
    String auth = botAuth();/*ww  w . j a v a2 s. co m*/
    String tagResponse = Request.Post(env.getProperty("bot.sendTag"))
            .addHeader("Authorization", "Bearer " + auth)
            .bodyString(dest.toString(), ContentType.APPLICATION_JSON).socketTimeout(20000).connectTimeout(5000)
            .execute().returnContent().asString();

    logger.info("Tag command sent to a bot {}, response {}", dest, tagResponse);
}

From source file:org.talend.dataprep.api.service.command.export.Export.java

/**
 * @param parameters the export parameters.
 * @return the request to perform.//from   w  w  w  . j  a  va2  s.  co  m
 */
private HttpRequestBase onExecute(ExportParameters parameters) {
    try {
        final String parametersAsString = objectMapper.writerFor(ExportParameters.class)
                .writeValueAsString(parameters);
        final HttpPost post = new HttpPost(transformationServiceUrl + "/apply");
        post.setEntity(new StringEntity(parametersAsString, ContentType.APPLICATION_JSON));
        return post;
    } catch (Exception e) {
        throw new TDPException(APIErrorCodes.UNABLE_TO_EXPORT_CONTENT, e);
    }
}

From source file:org.elasticsearch.client.RestHighLevelClientExtTests.java

public void testParseEntityCustomResponseSection() throws IOException {
    {/*from w ww .  j a  va  2  s  . co  m*/
        HttpEntity jsonEntity = new StringEntity("{\"custom1\":{ \"field\":\"value\"}}",
                ContentType.APPLICATION_JSON);
        BaseCustomResponseSection customSection = restHighLevelClient.parseEntity(jsonEntity,
                BaseCustomResponseSection::fromXContent);
        assertThat(customSection, instanceOf(CustomResponseSection1.class));
        CustomResponseSection1 customResponseSection1 = (CustomResponseSection1) customSection;
        assertEquals("value", customResponseSection1.value);
    }
    {
        HttpEntity jsonEntity = new StringEntity("{\"custom2\":{ \"array\": [\"item1\", \"item2\"]}}",
                ContentType.APPLICATION_JSON);
        BaseCustomResponseSection customSection = restHighLevelClient.parseEntity(jsonEntity,
                BaseCustomResponseSection::fromXContent);
        assertThat(customSection, instanceOf(CustomResponseSection2.class));
        CustomResponseSection2 customResponseSection2 = (CustomResponseSection2) customSection;
        assertArrayEquals(new String[] { "item1", "item2" }, customResponseSection2.values);
    }
}

From source file:com.keydap.sparrow.auth.SparrowAuthenticator.java

@Override
public void authenticate(String baseUrl, CloseableHttpClient client) throws Exception {
    HttpPost post = new HttpPost(baseUrl + "/directLogin");
    String body = new Gson().toJson(authReq);
    StringEntity entity = new StringEntity(body, ContentType.APPLICATION_JSON);
    post.setEntity(entity);/*from   w w  w  .j  av a  2 s  .c  o  m*/

    HttpResponse resp = client.execute(post);
    StatusLine sl = resp.getStatusLine();

    if ((sl.getStatusCode() != 200) && (sl.getStatusCode() != 201)) {
        String msg = "Authentication failed [code: %d, reason: %s]";
        msg = String.format(msg, sl.getStatusCode(), sl.getReasonPhrase());
        LOG.warn(msg);
        throw new IllegalStateException(msg);
    }

    LOG.debug("Successfully authenticated");
    token = EntityUtils.toString(resp.getEntity());
}

From source file:io.github.bckfnn.reactstreams.arangodb.AsyncHttpClient.java

@Override
public <T extends Result> Stream<T> process(Operation<T> req) {
    LOG.debug("req -> " + req.getUri());
    return Stream.asOne(subscription -> {
        HttpRequest request = null;/* w w  w  .j  a v  a2  s .  c o m*/
        if (req.getMethod().equals("POST")) {
            HttpPost post = new HttpPost(req.getUri());
            post.setEntity(
                    new ByteArrayEntity(mapper.writeValueAsBytes(req.getBody()), ContentType.APPLICATION_JSON));
            request = post;
        } else if (req.getMethod().equals("GET")) {
            request = new HttpGet(req.getUri());
        }

        httpClient.execute(new HttpHost(host, port), request, new FutureCallback<HttpResponse>() {
            public void completed(HttpResponse result) {
                LOG.debug("res <- " + result.getStatusLine().getStatusCode());
                HttpEntity ent = result.getEntity();
                System.out.println(result.getStatusLine().getStatusCode() + " " + ent.isRepeatable());

                try {
                    T val = mapper.readValue(ent.getContent(), req.getResponseClass());
                    subscription.sendNext(val);
                    subscription.sendComplete();
                } catch (Exception e) {
                    subscription.sendError(e);
                }
            }

            public void failed(Exception ex) {
                subscription.sendError(ex);
            }

            public void cancelled() {
                subscription.sendError(new Throwable("cancelled"));
            }
        });
    });
}

From source file:org.elasticsearch.client.RankEvalIT.java

@Before
public void indexDocuments() throws IOException {
    StringEntity doc = new StringEntity("{\"text\":\"berlin\"}", ContentType.APPLICATION_JSON);
    client().performRequest("PUT", "/index/doc/1", Collections.emptyMap(), doc);
    doc = new StringEntity("{\"text\":\"amsterdam\"}", ContentType.APPLICATION_JSON);
    client().performRequest("PUT", "/index/doc/2", Collections.emptyMap(), doc);
    client().performRequest("PUT", "/index/doc/3", Collections.emptyMap(), doc);
    client().performRequest("PUT", "/index/doc/4", Collections.emptyMap(), doc);
    client().performRequest("PUT", "/index/doc/5", Collections.emptyMap(), doc);
    client().performRequest("PUT", "/index/doc/6", Collections.emptyMap(), doc);
    client().performRequest("POST", "/index/_refresh");

    // add another index to test basic multi index support
    client().performRequest("PUT", "/index2/doc/7", Collections.emptyMap(), doc);
    client().performRequest("POST", "/index2/_refresh");
}