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:ai.api.twilio.BaseTwilioServlet.java

/**
 * Send request to api.ai/*  w  ww. ja va  2 s  .c o  m*/
 * 
 * @param query
 * @param parameters
 *            - parameters received from www.twilio.com
 * @return response from api.ai
 */
protected String sendRequestToApiAi(String query, Map<String, String[]> parameters) {
    HttpResponse response = null;
    try {
        StringEntity input = new StringEntity(createApiRequest(query, parameters),
                ContentType.APPLICATION_JSON);

        response = POOLING_HTTP_CLIENT.execute(RequestBuilder.post()
                .setUri(TwilioProperties.INSTANCE.getApiUrl())
                .addHeader("Authorization", "Bearer " + TwilioProperties.INSTANCE.getApiAccessToken())
                .addHeader("Accept", ContentType.APPLICATION_JSON.getMimeType()).setEntity(input).build());

        if (response.getStatusLine().getStatusCode() / 100 != 2) {
            return "Error: " + response.getStatusLine();
        }
        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        StringBuilder resultBuilder = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            resultBuilder.append(line);
        }

        ApiResponse resultResp = gson.fromJson(resultBuilder.toString(), ApiResponse.class);
        if (Strings.isNullOrEmpty(Optional.ofNullable(resultResp.result).map(r -> r.fulfillment)
                .map(f -> f.speech).orElse(null))) {
            return "Action: " + Optional.ofNullable(resultResp.result).map(r -> r.action).orElse("none") + "\n"
                    + gson.toJson(Optional.ofNullable(resultResp.result).map(r -> r.parameters)
                            .orElse(Collections.emptyMap()));
        }
        return resultResp.result.fulfillment.speech;
    } catch (IOException e) {
        LOGGER.error(e.getMessage());
        return "Error: " + e.getMessage();
    } finally {
        if (response != null) {
            try {
                EntityUtils.consume(response.getEntity());
            } catch (IOException e) {
                // Ignore
            }
        }
    }
}

From source file:com.meplato.store2.ApacheHttpClient.java

/**
 * Execute runs a HTTP request/response with an API endpoint.
 *
 * @param method      the HTTP method, e.g. POST or GET
 * @param uriTemplate the URI template according to RFC 6570
 * @param parameters  the query string parameters
 * @param headers     the key/value pairs for the HTTP header
 * @param body        the body of the request or {@code null}
 * @return the HTTP response encapsulated by {@link Response}.
 * @throws ServiceException if e.g. the service is unavailable.
 *//*  w w w  .ja  va 2  s  . c om*/
@Override
public Response execute(String method, String uriTemplate, Map<String, Object> parameters,
        Map<String, String> headers, Object body) throws ServiceException {
    // URI template parameters
    String url = UriTemplate.fromTemplate(uriTemplate).expand(parameters);

    // Body
    HttpEntity requestEntity = null;
    if (body != null) {
        Gson gson = getSerializer();
        try {
            requestEntity = EntityBuilder.create().setText(gson.toJson(body)).setContentEncoding("UTF-8")
                    .setContentType(ContentType.APPLICATION_JSON).build();
        } catch (Exception e) {
            throw new ServiceException("Error serializing body", null, e);
        }
    }

    // Do HTTP request
    HttpRequestBase httpRequest = null;
    if (method.equalsIgnoreCase("GET")) {
        httpRequest = new HttpGet(url);
    } else if (method.equalsIgnoreCase("POST")) {
        HttpPost httpPost = new HttpPost(url);
        if (requestEntity != null) {
            httpPost.setEntity(requestEntity);
        }
        httpRequest = httpPost;
    } else if (method.equalsIgnoreCase("PUT")) {
        HttpPut httpPut = new HttpPut(url);
        if (requestEntity != null) {
            httpPut.setEntity(requestEntity);
        }
        httpRequest = httpPut;
    } else if (method.equalsIgnoreCase("DELETE")) {
        httpRequest = new HttpDelete(url);
    } else if (method.equalsIgnoreCase("PATCH")) {
        HttpPatch httpPatch = new HttpPatch(url);
        if (requestEntity != null) {
            httpPatch.setEntity(requestEntity);
        }
        httpRequest = httpPatch;
    } else if (method.equalsIgnoreCase("HEAD")) {
        httpRequest = new HttpHead(url);
    } else if (method.equalsIgnoreCase("OPTIONS")) {
        httpRequest = new HttpOptions(url);
    } else {
        throw new ServiceException("Invalid HTTP method: " + method, null, null);
    }

    // Headers
    for (Map.Entry<String, String> entry : headers.entrySet()) {
        httpRequest.addHeader(entry.getKey(), entry.getValue());
    }
    httpRequest.setHeader("Accept", "application/json");
    httpRequest.setHeader("Accept-Charset", "utf-8");
    httpRequest.setHeader("Content-Type", "application/json; charset=utf-8");
    httpRequest.setHeader("User-Agent", USER_AGENT);

    try (CloseableHttpResponse httpResponse = httpClient.execute(httpRequest)) {
        Response response = new ApacheHttpResponse(httpResponse);
        int statusCode = response.getStatusCode();
        if (statusCode >= 200 && statusCode < 300) {
            return response;
        }
        throw ServiceException.fromResponse(response);
    } catch (ClientProtocolException e) {
        throw new ServiceException("Client Protocol Exception", null, e);
    } catch (IOException e) {
        throw new ServiceException("IO Exception", null, e);
    }
}

From source file:org.jboss.as.test.integration.management.interfaces.HttpManagementInterface.java

@Override
public ModelNode execute(ModelNode operation) {
    String operationJson = operation.toJSONString(true);
    try {//w  w w  .j a  v a2 s  .c om
        HttpPost post = new HttpPost(uri);
        post.setEntity(new StringEntity(operationJson, ContentType.APPLICATION_JSON));
        post.setHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.getMimeType());
        HttpResponse response = httpClient.execute(post);
        return parseResponse(response);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.biokoframework.http.exception.impl.ExceptionResponseBuilderTest.java

@Test
public void testBiokoExceptionWithErrorEntity() throws Exception {

    ExceptionResponseBuilderImpl builder = new ExceptionResponseBuilderImpl(fCodesMap);

    MockResponse mockResponse = new MockResponse();
    ErrorEntity error = new ErrorEntity();
    error.setAll(new Fields(ErrorEntity.ERROR_CODE, 12345, ErrorEntity.ERROR_MESSAGE, "Failed at life"));
    MockException mockException = new MockException(error);

    mockResponse = (MockResponse) builder.build(mockResponse, mockException, null, null);

    assertThat(mockResponse.getContentType(), is(equalTo(ContentType.APPLICATION_JSON.toString())));
    assertThat(mockResponse.getStatus(), is(equalTo(626)));
    assertThat(mockResponse, hasToString(equalTo(JSONValue.toJSONString(mockException.getErrors()))));
}

From source file:com.seyren.core.service.notification.VictorOpsNotificationService.java

@Override
public void sendNotification(Check check, Subscription subscription, List<Alert> alerts)
        throws NotificationFailedException {

    String victorOpsRestEndpoint = seyrenConfig.getVictorOpsRestEndpoint();
    String victorOpsRoutingKey = StringUtils.defaultIfEmpty(subscription.getTarget(), "default");

    if (victorOpsRestEndpoint == null) {
        LOGGER.warn("VictorOps REST API endpoint needs to be set before sending notifications");
        return;/*  w  w w.  j  av  a 2  s . c  o  m*/
    }

    URI victorOpsUri = null;
    try {
        victorOpsUri = new URI(victorOpsRestEndpoint).resolve(new URI(victorOpsRoutingKey));
    } catch (URISyntaxException use) {
        LOGGER.warn("Invalid endpoint is given.");
        return;
    }

    HttpClient client = HttpClientBuilder.create().useSystemProperties().build();
    HttpPost post = new HttpPost(victorOpsUri);
    try {
        HttpEntity entity = new StringEntity(getDescription(check, alerts), ContentType.APPLICATION_JSON);
        post.setEntity(entity);
        HttpResponse response = client.execute(post);
        HttpEntity responseEntity = response.getEntity();
        if (responseEntity != null) {
            LOGGER.info("Response : {} ", EntityUtils.toString(responseEntity));
        }
    } catch (Exception e) {
        throw new NotificationFailedException("Failed to send notification to VictorOps", e);
    } finally {
        post.releaseConnection();
        HttpClientUtils.closeQuietly(client);
    }
}

From source file:org.apache.gobblin.http.ApacheHttpRequestBuilder.java

public static ContentType createContentType(String contentType) {
    switch (contentType) {
    case "application/json":
        return ContentType.APPLICATION_JSON;
    case "text/plain":
        return ContentType.TEXT_PLAIN;
    default:/*w  w w  .j a va 2s  . c  o m*/
        throw new RuntimeException("contentType not supported: " + contentType);
    }
}

From source file:org.sentilo.platform.server.test.request.SentiloRequestHandlerTest.java

@Test
public void handler() throws Exception {
    when(httpRequest.getRequestLine()).thenReturn(requestLine);
    when(requestLine.getMethod()).thenReturn("GET");
    when(requestLine.getUri()).thenReturn("http://lab.sentilo.io/data/mock");
    when(handlerLocator.lookup(any(SentiloRequest.class))).thenReturn(handler);
    when(handler.getLogger()).thenReturn(logger);

    requestHandler.handle(httpRequest, httpResponse, httpContext);

    // verify(handler).manageRequest(any(SentiloRequest.class), any(SentiloResponse.class));
    verify(httpResponse).setStatusCode(HttpStatus.SC_OK);
    verify(httpResponse).setHeader(HttpHeader.CONTENT_TYPE.toString(), ContentType.APPLICATION_JSON.toString());

}

From source file:org.elasticsearch.xpack.ml.integration.DatafeedJobsRestIT.java

private void setupDataAccessRole(String index) throws IOException {
    String json = "{" + "  \"indices\" : [" + "    { \"names\": [\"" + index
            + "\"], \"privileges\": [\"read\"] }" + "  ]" + "}";

    client().performRequest("put", "_xpack/security/role/test_data_access", Collections.emptyMap(),
            new StringEntity(json, ContentType.APPLICATION_JSON));
}

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

@Test
public void call_case1_chunked_request() throws Exception {
    String testCase = "case1";

    InputStream is = this.getClass().getClassLoader().getResourceAsStream(testCase + "/request_content.json");
    Request request = Request.Post("http://localhost:8082/test/my_team?case=" + testCase).bodyStream(is,
            ContentType.APPLICATION_JSON);

    try {//from  w  w w  . j  a  va 2  s. c om
        Response response = request.execute();

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

        // Not a chunked response because body content is to small
        assertEquals(null, returnResponse.getFirstHeader(HttpHeaders.TRANSFER_ENCODING));
    } catch (Exception e) {
        e.printStackTrace();
        assertTrue(false);
    }
}