Example usage for org.apache.http.entity StringEntity setContentType

List of usage examples for org.apache.http.entity StringEntity setContentType

Introduction

In this page you can find the example usage for org.apache.http.entity StringEntity setContentType.

Prototype

public void setContentType(Header header) 

Source Link

Usage

From source file:Remote.java

public String sendCommandRaw(String request) {
    InputStream response = null;//  ww w  .  j a v  a2  s.  c  o m
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    String data = "ERROR";

    try {
        try {
            HttpPost httpRequest = new HttpPost(path);
            StringEntity httpParams = new StringEntity(request);
            httpParams.setContentType("application/json");
            httpRequest.setEntity(httpParams);
            response = httpClient.execute(httpRequest).getEntity().getContent();
            data = IOUtils.toString(response);
        } catch (Exception ex) {
            System.out.println(ex);
        } finally {
            httpClient.close();
        }
    } catch (IOException ex) {
        Logger.getLogger(Remote.class.getName()).log(Level.SEVERE, null, ex);
    }
    return data;
}

From source file:com.moarub.kipptapi.CreateClip.java

private HttpResponse doCreateClip(String... params) {
    String username = params[0];/*from w w w.  java 2  s . co m*/
    String token = params[1];
    String reqTokenUrl = "https://kippt.com/api/clips/";
    DefaultHttpClient client = new DefaultHttpClient();

    try {
        HttpPost request = new HttpPost(reqTokenUrl);
        request.addHeader("X-Kippt-Username", username);
        request.addHeader("X-Kippt-API-Token", token);
        request.addHeader("X-Kippt-Client",
                "ShareMore for Android,sharemore@moarub.com,http://moarub.com/sharemore");

        JSONObject job = new JSONObject();
        job.put("url", fClipUrl);
        if (fNote != null) {
            job.put("notes", fNote);
        }
        if (fTitle != null) {
            job.put("title", fTitle);
        }
        if (fReadLater) {
            job.put("is_read_later", true);
        }
        if (fStar) {
            job.put("is_starred", true);
        }
        if (fListResourceUri != null) {
            job.put("list", fListResourceUri);
        }

        StringEntity se = new StringEntity(job.toString(), "UTF-8");
        se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));

        Log.d("Sending clip JSON", job.toString());

        request.setEntity(se);

        return client.execute(request);
    } catch (ClientProtocolException e) {
        Log.d("ApiTokenFailure", "Can't fetch API Token");
        return null;
    } catch (IOException e) {
        Log.d("ApiTokenFailure", "Can't fetch API Token");
        return null;
    } catch (JSONException e) {
        Log.d("ApiTokenFailure", "Can't fetch API Token");
        return null;
    }
}

From source file:com.wso2telco.ussdstub.main.OutboundMobileMessage.java

private boolean postToNotifyURL(String jsonObj, String notifyURL) {
    try {/*from   ww w  . j ava2s. c  o m*/
        HttpPost post = new HttpPost(notifyURL);
        CloseableHttpClient httpclient = null;
        CloseableHttpResponse response = null;
        httpclient = HttpClients.createDefault();
        StringEntity strEntity = new StringEntity(jsonObj.toString(), "UTF-8");
        strEntity.setContentType("application/json");
        post.setEntity((HttpEntity) strEntity);
        LOG.info((Object) ("notify URL: " + notifyURL));
        response = httpclient.execute((HttpUriRequest) post);
        HttpEntity entity = response.getEntity();
        InputStream instream = entity.getContent();
        StringWriter writer = new StringWriter();
        IOUtils.copy((Reader) new InputStreamReader(instream), (Writer) writer, (int) 1024);
        String body = writer.toString();
        LOG.info((Object) ("jsonbody returned: " + body));
        JSONObject replyJsonObj = new JSONObject(body);
        String senderAddress = replyJsonObj.getJSONObject("outboundUSSDMessageRequest").getString("address");

        (new Endpoints()).addRequest(body, senderAddress);
        if (!body.isEmpty()) {
            LOG.info((Object) "json body is not empty");
            return true;
        }
    } catch (IOException ex) {
        ex.printStackTrace();
        return false;
    }
    return false;
}

From source file:de.lgblaumeiser.ptm.cli.rest.RestUtils.java

/**
 * Post a call to the rest api. Expects that a numerical id is returned as
 * part of the creation call.// w w w  .  java  2s .c  o m
 * 
 * @param apiName
 *            Name of the api
 * @param bodyData
 *            Body of the post data, this is a flat map that is converted
 *            into a flat json
 * @return The Id of the created or manipulated object
 */
public Long post(String apiName, Map<String, String> bodyData) {
    try {
        final HttpPost request = new HttpPost(baseUrl + apiName);
        StringEntity bodyJson = new StringEntity(jsonMapper.writeValueAsString(bodyData));
        bodyJson.setContentType("application/json");
        bodyJson.setContentEncoding("UTF-8");
        request.setEntity(bodyJson);
        HttpResponse response = clientConnector.execute(request);
        checkState(
                response.getStatusLine().getStatusCode() == 201
                        || response.getStatusLine().getStatusCode() == 200,
                "Cannot access server properly, Status " + response.getStatusLine() + ", URI: " + apiName);
        String uri = apiName;
        if (response.getStatusLine().getStatusCode() == 201) {
            uri = response.getHeaders("Location")[0].getValue();
        }
        return Long.parseLong(uri.substring(uri.lastIndexOf("/") + 1));
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }

}

From source file:org.fcrepo.storage.policy.FedoraStoragePolicyIT.java

@Test
public void testPolicyCreateByPost() throws Exception {
    final HttpPost objMethod = HttpPostObjMethod(POLICY_RESOURCE);
    StringEntity input = new StringEntity(MIME_KEY + " " + MIME + " " + STORE, "UTF-8");
    input.setContentType(APPLICATION_FORM_URLENCODED);
    objMethod.setEntity(input);/*from w  w w  .  j  a  va2s  .c o  m*/
    final HttpResponse response = client.execute(objMethod);

    String body = IOUtils.toString(response.getEntity().getContent());
    assertEquals(body, 201, response.getStatusLine().getStatusCode());

    policyKeys.add(MIME_KEY);

    Header[] headers = response.getHeaders("Location");
    assertNotNull(headers);
    assertEquals(1, headers.length);
    assertEquals(objMethod.getURI().toString().replace(POLICY_RESOURCE, MIME_KEY), headers[0].getValue());
}

From source file:org.jfrog.build.client.ArtifactoryDependenciesClient.java

/**
 * Retrieves list of {@link org.jfrog.build.api.dependency.BuildPatternArtifacts} for build dependencies specified.
 *
 * @param requests build dependencies to retrieve outputs for.
 * @return build outputs for dependencies specified.
 * @throws java.io.IOException/*w ww.ja  v  a  2 s .  c  o m*/
 */
public List<BuildPatternArtifacts> retrievePatternArtifacts(List<BuildPatternArtifactsRequest> requests)
        throws IOException {
    final String json = new JsonSerializer<List<BuildPatternArtifactsRequest>>().toJSON(requests);
    final HttpPost post = new HttpPost(artifactoryUrl + "/api/build/patternArtifacts");

    StringEntity stringEntity = new StringEntity(json);
    stringEntity.setContentType("application/vnd.org.jfrog.artifactory+json");
    post.setEntity(stringEntity);

    List<BuildPatternArtifacts> artifacts = readResponse(httpClient.getHttpClient().execute(post),
            new TypeReference<List<BuildPatternArtifacts>>() {
            }, "Failed to retrieve build artifacts report");
    return artifacts;
}

From source file:com.supermap.desktop.icloud.impl.LicenseServiceImpl.java

/**
 * ?/*w w  w .  jav  a  2  s  .c  o  m*/
 *
 * @param request
 * @return
 * @throws IOException
 */
public ServiceResponse<ApplyTrialLicenseResponse> apply(ApplyTrialLicenseRequest request) throws IOException {
    ValidationUtil.validate(request);
    String url = baseUrl + "/trial/ids" + this.appKey;
    HttpPost postRequest = new HttpPost(url);
    String jsonBody = CloudLicenseJSON.toJSONString(request);
    StringEntity body = new StringEntity(jsonBody, UTF8);
    body.setContentType(JSON_UTF8_CONTENT_TPYE);
    postRequest.setEntity(body);
    CloseableHttpResponse response = this.client.execute(postRequest);
    String json = getJsonStrFromResponse(response);
    return (ServiceResponse) CloudLicenseJSON.parseObject(json, APPLY_TRIAL_RESPONSE_TYPE, new Feature[0]);
}

From source file:at.sti2.spark.handler.SupportHandler.java

private void sendToREST(String url, String content) {

    //HTTP Post//  w  w  w.  jav a  2  s  .c om
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);

    try {
        StringEntity postStringEntity = new StringEntity(content);
        postStringEntity.setContentType("text/xml");

        httpPost.addHeader("Accept", "*/*");
        httpPost.setEntity(postStringEntity);
        HttpResponse response = httpclient.execute(httpPost);

        logger.info("[POSTING Event] Status code " + response.getStatusLine());

        //First invocation succeeded
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

            HttpEntity entityResponse = response.getEntity();

            //Something has been returned, let's see what is in it
            if (entityResponse != null) {
                String stringResponse = EntityUtils.toString(entityResponse);
                logger.debug("Response " + stringResponse);
            }
        }
    } catch (UnsupportedEncodingException e) {
        logger.error(e.getMessage());
    } catch (ClientProtocolException e) {
        logger.error(e.getMessage());
    } catch (IOException e) {
        logger.error(e.getMessage());
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:boosta.artem.services.TaskQuery.java

public String getStatus(int id) throws UnsupportedEncodingException, IOException, ParseException {

    String result = "{\n" + "  \"password\" : \"\",\n" + "  \"action\" : \"getTaskState\",\n"
            + "  \"data\" : {\n" + "      \"taskUid\" : \"" + String.valueOf(id) + "\"\n" + "  }\n" + "}";

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost("http://62.210.82.210:9091/API");

    StringEntity requestEntity = new StringEntity(result);
    requestEntity.setContentType("application/json");
    httpPost.setEntity(requestEntity);//from   w ww .  j  a va  2  s .co  m
    HttpResponse response = httpClient.execute(httpPost);

    InputStream in = response.getEntity().getContent();

    //System.out.println(getStringFromInputStream(in));

    String resp = getStringFromInputStream(in);

    JSONParser parser = new JSONParser();

    JSONObject json = (JSONObject) parser.parse(resp);
    json = (JSONObject) json.get("data");
    String status = json.get("status").toString();

    System.out.println(status);
    //return getStringFromInputStream(in);

    return status;
}

From source file:boosta.artem.services.TaskQuery.java

public int getResultCounts(int id) throws UnsupportedEncodingException, IOException, ParseException {

    String result = "{\n" + "  \"password\" : \"\",\n" + "  \"action\" : \"getTaskState\",\n"
            + "  \"data\" : {\n" + "      \"taskUid\" : \"" + String.valueOf(id) + "\"\n" + "  }\n" + "}";

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost("http://62.210.82.210:9091/API");

    StringEntity requestEntity = new StringEntity(result);
    requestEntity.setContentType("application/json");
    httpPost.setEntity(requestEntity);/*  w w w.  java  2  s .  c  om*/
    HttpResponse response = httpClient.execute(httpPost);

    InputStream in = response.getEntity().getContent();

    //System.out.println(getStringFromInputStream(in));

    String resp = getStringFromInputStream(in);

    JSONParser parser = new JSONParser();

    JSONObject json = (JSONObject) parser.parse(resp);
    json = (JSONObject) json.get("data");
    json = (JSONObject) json.get("state");
    int counts = Integer.parseInt(json.get("resultsCount").toString());

    System.out.println(counts);
    //return getStringFromInputStream(in);

    return counts;
}