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:io.restassured.internal.http.EncoderRegistry.java

/**
 * Helper method used by encoder methods to create an {@link HttpEntity}
 * instance that encapsulates the request data.  This may be used by any
 * non-streaming encoder that needs to send textual data.
 *
 * @param ct   content-type of the data/* w  ww  . j  a  v a 2 s.  co m*/
 * @param data textual request data to be encoded
 * @return an instance to be used for the
 * {@link HttpEntityEnclosingRequest#setEntity(HttpEntity) request content}
 * @throws UnsupportedEncodingException
 */
protected HttpEntity createEntity(String ct, String data) throws UnsupportedEncodingException {
    String charset = CharsetExtractor.getCharsetFromContentType(ct);
    if (charset == null) {
        if (encoderConfig.hasDefaultCharsetForContentType(ct)) {
            charset = encoderConfig.defaultCharsetForContentType(ct);
        } else {
            charset = encoderConfig.defaultContentCharset();
        }
    }
    StringEntity entity = new StringEntity(data, charset);
    entity.setContentType(ct);
    return entity;
}

From source file:com.networknt.light.rule.LoadRuleMojo.java

private void impRule(String ruleClass, String sourceCode) {

    Map<String, Object> inputMap = new HashMap<String, Object>();
    inputMap.put("category", "rule");
    inputMap.put("name", "impRule");
    inputMap.put("readOnly", false);
    Map<String, Object> data = new HashMap<String, Object>();
    data.put("ruleClass", ruleClass);
    data.put("sourceCode", sourceCode);
    inputMap.put("data", data);

    CloseableHttpResponse response = null;
    try {/*w ww .j  a  va 2 s.com*/
        HttpPost httpPost = new HttpPost(serverUrl + "/api/rs");
        httpPost.addHeader("Authorization", "Bearer " + jwt);
        StringEntity input = new StringEntity(mapper.writeValueAsString(inputMap));
        input.setContentType("application/json");
        httpPost.setEntity(input);
        response = httpclient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent()));
        String json = "";
        String line = "";
        while ((line = rd.readLine()) != null) {
            json = json + line;
        }
        EntityUtils.consume(entity);
        System.out.println("Loaded " + ruleClass);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.networknt.light.rule.LoadRuleMojo.java

/**
 * Get all rules from the server and construct a map in order to compare source code
 * to detect changes or not.//ww w  .  ja v  a2s  . c  o  m
 *
 * @return Map<String, String>
 */
private Map<String, String> getRuleMap() {
    Map<String, String> ruleMap = null;

    Map<String, Object> inputMap = new HashMap<String, Object>();
    inputMap.put("category", "rule");
    inputMap.put("name", "getRuleMap");
    inputMap.put("readOnly", true);

    CloseableHttpResponse response = null;
    try {
        HttpPost httpPost = new HttpPost(serverUrl + "/api/rs");
        httpPost.addHeader("Authorization", "Bearer " + jwt);
        StringEntity input = new StringEntity(mapper.writeValueAsString(inputMap));
        input.setContentType("application/json");
        httpPost.setEntity(input);
        response = httpclient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent()));
        String json = "";
        String line = "";
        while ((line = rd.readLine()) != null) {
            json = json + line;
        }
        EntityUtils.consume(entity);
        System.out.println("Got rule map from server");
        ruleMap = mapper.readValue(json, new TypeReference<HashMap<String, String>>() {
        });
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    return ruleMap;
}

From source file:org.opentraces.metatracker.net.OpenTracesClient.java

/**
 * Do XML over HTTP request and retun response.
 *//*from w ww .  j  a  v a  2  s.  c  o  m*/
private Element doRequest(Element anElement) throws ClientException {

    // Create URL to use
    String url = protocolURL;
    if (agentKey != null) {
        url = url + "?agentkey=" + agentKey;
    } else {
        // Must be login
        url = url + "?timeout=" + timeout;
    }
    p("doRequest: " + url + " req=" + anElement.getTagName());

    // Perform request/response
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);

    Element replyElement = null;

    try {
        // Make sure the server knows what kind of a response we will accept
        httpPost.addHeader("Accept", "text/xml");

        // Also be sure to tell the server what kind of content we are sending
        httpPost.addHeader("Content-Type", "application/xml");

        String xmlString = DOMUtil.dom2String(anElement.getOwnerDocument());

        StringEntity entity = new StringEntity(xmlString, "UTF-8");
        entity.setContentType("application/xml");
        httpPost.setEntity(entity);

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httpPost);

        // Parse response
        Document replyDoc = DOMUtil.parse(response.getEntity().getContent());
        replyElement = replyDoc.getDocumentElement();
        p("doRequest: rsp=" + replyElement.getTagName());
    } catch (Throwable t) {
        throw new ClientException("Error in doRequest: " + t);
    } finally {

    }

    return replyElement;

}

From source file:com.networknt.light.rule.LoadRuleMojo.java

private void login() {
    // login to the server
    Map<String, Object> inputMap = new HashMap<String, Object>();
    inputMap.put("category", "user");
    inputMap.put("name", "signInUser");
    inputMap.put("readOnly", false);
    Map<String, Object> data = new HashMap<String, Object>();
    data.put("userIdEmail", serverUser);
    data.put("password", serverPass);
    data.put("rememberMe", true);
    data.put("clientId", clientId);
    inputMap.put("data", data);

    CloseableHttpResponse response = null;
    try {/*from  w  ww .  j  av  a 2  s  . com*/
        HttpPost httpPost = new HttpPost(serverUrl + "/api/rs");
        StringEntity input = new StringEntity(mapper.writeValueAsString(inputMap));
        input.setContentType("application/json");
        httpPost.setEntity(input);
        response = httpclient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent()));
        String json = "";
        String line = "";
        while ((line = rd.readLine()) != null) {
            json = json + line;
        }
        Map<String, Object> jsonMap = mapper.readValue(json, new TypeReference<HashMap<String, Object>>() {
        });
        jwt = (String) jsonMap.get("accessToken");
        EntityUtils.consume(entity);
        System.out.println("Logged in successfully");
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:org.jclouds.http.apachehc.ApacheHCUtils.java

public void addEntityForContent(HttpEntityEnclosingRequest apacheRequest, Payload payload) {
    payload = payload instanceof DelegatingPayload ? DelegatingPayload.class.cast(payload).getDelegate()
            : payload;//  w ww .  j a  va 2s .  c o m
    if (payload instanceof StringPayload) {
        StringEntity nStringEntity = null;
        try {
            nStringEntity = new StringEntity((String) payload.getRawContent());
        } catch (UnsupportedEncodingException e) {
            throw new UnsupportedOperationException("Encoding not supported", e);
        }
        nStringEntity.setContentType(payload.getContentMetadata().getContentType());
        apacheRequest.setEntity(nStringEntity);
    } else if (payload instanceof FilePayload) {
        apacheRequest.setEntity(
                new FileEntity((File) payload.getRawContent(), payload.getContentMetadata().getContentType()));
    } else if (payload instanceof ByteArrayPayload) {
        ByteArrayEntity Entity = new ByteArrayEntity((byte[]) payload.getRawContent());
        Entity.setContentType(payload.getContentMetadata().getContentType());
        apacheRequest.setEntity(Entity);
    } else {
        InputStream inputStream = payload.getInput();
        if (payload.getContentMetadata().getContentLength() == null)
            throw new IllegalArgumentException("you must specify size when content is an InputStream");
        InputStreamEntity entity = new InputStreamEntity(inputStream,
                payload.getContentMetadata().getContentLength());
        entity.setContentType(payload.getContentMetadata().getContentType());
        apacheRequest.setEntity(entity);
    }

    // TODO Reproducing old behaviour exactly; ignoring Content-Type, Content-Length and Content-MD5
    Set<String> desiredHeaders = ImmutableSet.of("Content-Disposition", "Content-Encoding", "Content-Language",
            "Expires");
    MutableContentMetadata md = payload.getContentMetadata();
    for (Map.Entry<String, String> entry : contentMetadataCodec.toHeaders(md).entries()) {
        if (desiredHeaders.contains(entry.getKey())) {
            apacheRequest.addHeader(entry.getKey(), entry.getValue());
        }
    }

    assert apacheRequest.getEntity() != null;
}

From source file:org.jboss.tools.aerogear.hybrid.core.plugin.registry.CordovaPluginRegistryManager.java

private void updateDownlodCounter(String pluginId) {
    if (!registry.contains("registry.cordova.io"))//ping only cordova registry
        return;/*ww  w. java2s .c o  m*/

    HttpClient client = new DefaultHttpClient();
    String url = registry.endsWith("/") ? registry + "downloads" : registry + "/downloads";
    HttpPost post = new HttpPost(url);
    Date now = new Date();
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM.dd");
    df.setTimeZone(TimeZone.getTimeZone("UTC"));

    JsonObject obj = new JsonObject();
    obj.addProperty("day", df.format(now));
    obj.addProperty("pkg", pluginId);
    obj.addProperty("client", REGISTRY_CLIENT_ID);
    Gson gson = new Gson();
    String json = gson.toJson(obj);
    StringEntity entity;
    try {
        entity = new StringEntity(json);
        entity.setContentType("application/json");
        post.setEntity(entity);
        HttpResponse response = client.execute(post);
        if (response.getStatusLine().getStatusCode() != 201) {
            HybridCore.log(IStatus.INFO, "Unable to ping Cordova registry download counter", null);
        }
    } catch (UnsupportedEncodingException e) {
        HybridCore.log(IStatus.INFO, "Unable to ping Cordova registry download counter", e);
    } catch (IOException e) {
        HybridCore.log(IStatus.INFO, "Unable to ping Cordova registry download counter", e);
    }
}

From source file:com.google.resting.method.post.PostServiceContext.java

private HttpEntity setMessageEntity(String message, EncodingTypes encoding, ContentType contentType) {
    StringEntity entity = null;
    try {/*from   w  ww  .ja v a  2s.co m*/
        try {
            entity = new StringEntity(message);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (encoding != null)
            entity.setContentEncoding(encoding.getName());

        if (contentType != null)
            entity.setContentType(contentType.getName());

    } catch (Exception e) {
        e.printStackTrace();
    }
    return entity;
}

From source file:com.glodon.paas.document.api.AbstractDocumentAPITest.java

private void setHttpBody(HttpEntityEnclosingRequestBase requestBase, JSONObject body) {
    if (body != null) {
        try {/*from  w ww  .  ja v  a  2 s  . c  om*/
            StringEntity entity = new StringEntity(body.toString());
            entity.setContentType("application/json");
            entity.setContentEncoding("UTF-8");
            requestBase.setEntity(entity);
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage());
        }
    }
}

From source file:com.okta.tools.awscli.java

private static CloseableHttpResponse authnticateCredentials(String username, String password)
        throws JSONException, ClientProtocolException, IOException {
    HttpPost httpost = null;/*from w  ww  . jav a  2s .  c om*/
    CloseableHttpClient httpClient = HttpClients.createDefault();

    //HTTP Post request to Okta API for session token
    httpost = new HttpPost("https://" + oktaOrg + "/api/v1/authn");
    httpost.addHeader("Accept", "application/json");
    httpost.addHeader("Content-Type", "application/json");
    httpost.addHeader("Cache-Control", "no-cache");

    //construction of request JSON
    JSONObject jsonObjRequest = new JSONObject();
    jsonObjRequest.put("username", username);
    jsonObjRequest.put("password", password);

    StringEntity entity = new StringEntity(jsonObjRequest.toString(), StandardCharsets.UTF_8);
    entity.setContentType("application/json");
    httpost.setEntity(entity);

    return httpClient.execute(httpost);
}