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:com.huawei.ais.demo.TokenDemo.java

/**
 * ?Base64???Token???/*from  w  ww .  j av  a 2 s.  c o m*/
 * @param token token?
 * @param formFile 
 * @throws IOException
 */
public static void requestOcrIDCardBase64(String token, String formFile) {

    // 1.????
    String url = "https://ais.cn-north-1.myhuaweicloud.com/v1.0/ocr/id-card";
    Header[] headers = new Header[] { new BasicHeader("X-Auth-Token", token),
            new BasicHeader("Content-Type", ContentType.APPLICATION_JSON.toString()) };
    try {
        byte[] fileData = FileUtils.readFileToByteArray(new File(formFile));
        String fileBase64Str = Base64.encodeBase64String(fileData);
        JSONObject json = new JSONObject();
        json.put("image", fileBase64Str);

        //
        // ?????????
        // "side"?"front", "back"""?""??
        //
        json.put("side", "front");

        StringEntity stringEntity = new StringEntity(json.toJSONString(), "utf-8");

        // 2.???, POST??
        HttpResponse response = HttpClientUtils.post(url, headers, stringEntity);
        System.out.println(response);
        String content = IOUtils.toString(response.getEntity().getContent());
        System.out.println(content);
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:org.megam.deccanplato.provider.salesforce.crm.handler.OpportunitiesImpl.java

/**
 * This method updates a opportunity in salesforce.com and returns a success message with event opportunity id.
 * This method gets input from a MAP(contains json data) and returns a MAp.
 * @param outMap // w w w .  jav a  2  s. c om
 */
private Map<String, String> update() {
    Map<String, String> outMap = new HashMap<>();
    final String SALESFORCE_UPDATE_OPPORTUNITY_URL = args.get(INSTANCE_URL) + SALESFORCE_OPPORTUNITY_URL
            + args.get(ID);
    Map<String, String> header = new HashMap<String, String>();
    header.put(S_AUTHORIZATION, S_OAUTH + args.get(ACCESS_TOKEN));
    Map<String, Object> userAttrMap = new HashMap<String, Object>();
    userAttrMap.put(S_STAGENAME, args.get(STAGE_NAME));

    TransportTools tst = new TransportTools(SALESFORCE_UPDATE_OPPORTUNITY_URL, null, header);
    Gson obj = new GsonBuilder().setPrettyPrinting().create();
    tst.setContentType(ContentType.APPLICATION_JSON, obj.toJson(userAttrMap));
    try {
        TransportMachinery.patch(tst);
        outMap.put(OUTPUT, UPDATE_STRING + args.get(ID));

    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return outMap;
}

From source file:org.sentilo.platform.server.request.SentiloRequest.java

private ContentType getDefaultContentType() {
    return ContentType.APPLICATION_JSON;
}

From source file:de.elomagic.carafile.server.bl.RegistryClientBean.java

/**
 * Register this peer at the registry.//w ww .  j  a  v a2s .co m
 * <p/>
 * To registry a peer is very important. Otherwise no other peers will find you.
 *
 * @throws IOException Thrown when unable to call REST service at the registry
 * @throws java.net.URISyntaxException When unable to read URI
 */
public void registerPeer() throws IOException, URISyntaxException {
    LOG.debug("Registering this peer " + ownPeerURI + " at registry " + registryURI);

    PeerData peerData = new PeerData();
    peerData.setPeerURI(UriBuilder.fromUri(ownPeerURI).build());

    if (ownPeerURI.equalsIgnoreCase(registryURI)) {
        registryBean.registerPeer(peerData);
    } else {
        URI registry = UriBuilder.fromUri(registryURI).path(REGISTRY).path("registerPeer").build();
        HttpResponse response = Request.Post(registry)
                .bodyString(JsonUtil.write(peerData), ContentType.APPLICATION_JSON).execute().returnResponse();

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            LOG.debug("Peer registration successful");
        } else {
            LOG.error("Unable to registry peer at registry. Status Code "
                    + response.getStatusLine().getStatusCode() + ";Phrase="
                    + response.getStatusLine().getReasonPhrase());
        }
    }
}

From source file:com.thinkbiganalytics.search.ElasticSearchRestService.java

@Override
public void index(@Nonnull String indexName, @Nonnull String typeName, @Nonnull String id,
        @Nonnull Map<String, Object> fields) {
    buildRestClient();/*from w w  w.ja va  2s  .c om*/
    try {
        JSONObject jsonContent = new JSONObject(fields);
        HttpEntity httpEntity = new NStringEntity(jsonContent.toString(), ContentType.APPLICATION_JSON);
        restClient.performRequest(PUT_METHOD, getIndexWriteEndPoint(indexName, typeName, id),
                Collections.emptyMap(), httpEntity);
        log.debug("Wrote to index with name {}", indexName);
    } catch (ResponseException responseException) {
        log.warn("Index write encountered issues in Elasticsearch for index={" + indexName + "}, type={"
                + typeName + "}, id={" + id + "}", responseException);
    } catch (ClientProtocolException clientProtocolException) {
        log.debug("Http protocol error for write for index {" + indexName + "}", clientProtocolException);
    } catch (IOException ioException) {
        log.error("IO Error in rest client", ioException);
    } finally {
        closeRestClient();
    }
}

From source file:com.rackspacecloud.blueflood.outputs.handlers.HttpRollupHandlerIntegrationTest.java

public static void testHappyCaseMultiFetchHTTPRequest(List<Locator> locators, String tenantId,
        DefaultHttpClient client) throws Exception {
    HttpPost post = new HttpPost(getBatchMetricsQueryURI(tenantId));
    JSONArray metricsToGet = new JSONArray();
    for (Locator locator : locators) {
        metricsToGet.add(locator.toString());
    }//from   w  w w.j av  a  2s. co m
    HttpEntity entity = new StringEntity(metricsToGet.toString(), ContentType.APPLICATION_JSON);
    post.setEntity(entity);
    HttpResponse response = client.execute(post);
    Assert.assertEquals(200, response.getStatusLine().getStatusCode());
}

From source file:cf.client.DefaultCloudController.java

@Override
public UUID createService(Token token, Service service) {
    try {/* w w  w  .j  a v a  2  s .  c  om*/
        final String requestString = mapper.writeValueAsString(service);
        final HttpPost post = new HttpPost(target.resolve(V2_SERVICES));
        post.addHeader(token.toAuthorizationHeader());
        post.setEntity(new StringEntity(requestString, ContentType.APPLICATION_JSON));
        final HttpResponse response = httpClient.execute(post);
        try {
            validateResponse(response, 201);
            final JsonNode json = mapper.readTree(response.getEntity().getContent());
            return UUID.fromString(json.get("metadata").get("guid").asText());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.hp.octane.integrations.services.tasking.TasksProcessorImpl.java

@Override
public OctaneResultAbridged execute(OctaneTaskAbridged task) {
    if (task == null) {
        throw new IllegalArgumentException("task MUST NOT be null");
    }/*from w w  w  .  ja v a  2  s  .  co  m*/
    if (task.getUrl() == null || task.getUrl().isEmpty()) {
        throw new IllegalArgumentException("task 'URL' MUST NOT be null nor empty");
    }
    if (!task.getUrl().contains(NGA_API)) {
        throw new IllegalArgumentException(
                "task 'URL' expected to contain '" + NGA_API + "'; wrong handler call?");
    }
    logger.info("processing task '" + task.getId() + "': " + task.getMethod() + " " + task.getUrl());

    OctaneResultAbridged result = DTOFactory.getInstance().newDTO(OctaneResultAbridged.class);
    result.setId(task.getId());
    result.setStatus(200);
    result.setHeaders(new HashMap<>());
    String[] path = pathTokenizer(task.getUrl());
    try {
        if (path.length == 1 && STATUS.equals(path[0])) {
            executeStatusRequest(result);
        } else if (path.length == 1 && SUSPEND_STATUS.equals(path[0])) {
            suspendCiEvents(result, task.getBody());
        } else if (path[0].startsWith(JOBS)) {
            if (path.length == 1) {
                executeJobsListRequest(result, !path[0].contains("parameters=false"));
            } else if (path.length == 2) {
                executePipelineRequest(result, path[1]);
            } else if (path.length == 3 && RUN.equals(path[2])) {
                executePipelineRunRequest(result, path[1], task.getBody());
            } else if (path.length == 4 && BUILDS.equals(path[2])) {
                //TODO: in the future should take the last parameter from the request
                if (LATEST.equals(path[3])) {
                    executeLatestSnapshotRequest(result, path[1]);
                } else {
                    executeSnapshotByNumberRequest(result, path[1], path[3]);
                }
            } else {
                result.setStatus(404);
            }

        } else if (EXECUTOR.equalsIgnoreCase(path[0])) {
            if (HttpMethod.POST.equals(task.getMethod()) && path.length == 2) {
                if (INIT.equalsIgnoreCase(path[1])) {
                    DiscoveryInfo discoveryInfo = dtoFactory.dtoFromJson(task.getBody(), DiscoveryInfo.class);
                    discoveryInfo.setConfigurationId(configurer.octaneConfiguration.getInstanceId());
                    configurer.pluginServices.runTestDiscovery(discoveryInfo);
                    PipelineNode node = configurer.pluginServices.createExecutor(discoveryInfo);
                    if (node != null) {
                        result.setBody(dtoFactory.dtoToJson(node));
                        result.getHeaders().put(HttpHeaders.CONTENT_TYPE,
                                ContentType.APPLICATION_JSON.getMimeType());
                    }
                    result.setStatus(200);
                } else if (SUITE_RUN.equalsIgnoreCase(path[1])) {
                    TestSuiteExecutionInfo testSuiteExecutionInfo = dtoFactory.dtoFromJson(task.getBody(),
                            TestSuiteExecutionInfo.class);
                    configurer.pluginServices.runTestSuiteExecution(testSuiteExecutionInfo);
                    result.setStatus(200);
                } else if (TEST_CONN.equalsIgnoreCase(path[1])) {
                    TestConnectivityInfo testConnectivityInfo = dtoFactory.dtoFromJson(task.getBody(),
                            TestConnectivityInfo.class);
                    OctaneResponse connTestResult = configurer.pluginServices
                            .checkRepositoryConnectivity(testConnectivityInfo);
                    result.setStatus(connTestResult.getStatus());
                    result.setBody(connTestResult.getBody());
                } else if (CREDENTIALS_UPSERT.equalsIgnoreCase(path[1])) {
                    CredentialsInfo credentialsInfo = dtoFactory.dtoFromJson(task.getBody(),
                            CredentialsInfo.class);
                    executeUpsertCredentials(result, credentialsInfo);

                } else {
                    result.setStatus(404);
                }
            } else if (HttpMethod.DELETE.equals(task.getMethod()) && path.length == 2) {
                String id = path[1];
                configurer.pluginServices.deleteExecutor(id);
            }

        } else {
            result.setStatus(404);
        }
    } catch (PermissionException pe) {
        logger.warn("task execution failed; error: " + pe.getErrorCode());
        result.setStatus(pe.getErrorCode());
        result.setBody(String.valueOf(pe.getErrorCode()));
    } catch (ConfigurationException ce) {
        logger.warn("task execution failed; error: " + ce.getErrorCode());
        result.setStatus(ce.getErrorCode());
        result.setBody(String.valueOf(ce.getErrorCode()));
    } catch (Exception e) {
        logger.error("task execution failed", e);
        result.setStatus(500);
    }

    logger.info("result for task '" + task.getId() + "' available with status " + result.getStatus());
    return result;
}

From source file:de.retresco.shift.ShiftClient.java

/**
 * Add a new image to the SHIFT backend.
 *
 * @param image The image to add./*w  w  w .  ja  v  a2  s .c  o m*/
 */
public boolean addImage(final Image image) throws ShiftClientException, ShiftDataViolation {
    final HttpPost post = new HttpPost(this.imageUrl);

    try {
        final HttpEntity body = new StringEntity(image.toJson(), ContentType.APPLICATION_JSON);
        post.setEntity(body);
    } catch (final IOException e) {
        // TODO throw specialized exception
        throw new ShiftClientException(e);
    }

    final HttpResponse response = executeRequest(post);
    return response.getStatusLine().getStatusCode() == 200;
}

From source file:com.graphaware.test.util.TestUtils.java

/**
 * Issue an HTTP PUT and assert the response status code.
 *
 * @param url                to POST to.
 * @param json               request body.
 * @param headers            request headers as map.
 * @param expectedStatusCode expected status code.
 * @return the body of the response.//w w  w .j  a  v  a2  s .c  o m
 */
public static String put(String url, String json, Map<String, String> headers, final int expectedStatusCode) {
    HttpPut put = new HttpPut(url);
    if (json != null) {
        put.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON));
    }

    setHeaders(put, headers);

    return method(put, expectedStatusCode);
}