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:com.networknt.light.server.handler.loader.FormLoader.java

/**
 * Get all forms from the server and construct a map in order to compare content
 * to detect changes or not./*from  w  w w .j a v  a  2 s .  c  om*/
 *
 */
private static void getFormMap(String host) {

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

    CloseableHttpResponse response = null;
    try {
        HttpPost httpPost = new HttpPost(host + "/api/rs");
        httpPost.addHeader("Authorization", "Bearer " + jwt);
        StringEntity input = new StringEntity(
                ServiceLocator.getInstance().getMapper().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 form map from server");
        if (json != null && json.trim().length() > 0) {
            formMap = ServiceLocator.getInstance().getMapper().readValue(json,
                    new TypeReference<HashMap<String, Map<String, Object>>>() {
                    });
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:it.smartcommunitylab.carpooling.controllers.UserAuthController.java

public static HttpResponse postJSON(String url, String body) throws Exception {

    final HttpResponse resp;
    final HttpPost post = new HttpPost(url);

    post.setHeader("Accept", "application/json");
    post.setHeader("Content-Type", "application/json");

    StringEntity input = new StringEntity(body, "UTF-8");
    input.setContentType("application/json");
    post.setEntity(input);// w w  w .  j  a  va 2  s . c o m

    HttpClient httpClient = new DefaultHttpClient();
    final HttpParams params = httpClient.getParams();
    HttpConnectionParams.setConnectionTimeout(params, 30000);
    HttpConnectionParams.setSoTimeout(params, 30000);
    ConnManagerParams.setTimeout(params, 30000);

    resp = httpClient.execute(post);
    return resp;
}

From source file:com.cloudhopper.httpclient.util.HttpSender.java

static public Response postXml(String url, String username, String password, String requestXml)
        throws Exception {
    ///*from  w w w.  j  a  va 2  s  .  c o m*/
    // trust any SSL connection
    //
    TrustManager easyTrustManager = new X509TrustManager() {
        public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                throws CertificateException {
            // allow all
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                throws CertificateException {
            // allow all
        }

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };

    Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);
    SSLContext sslcontext = SSLContext.getInstance("TLS");
    sslcontext.init(null, new TrustManager[] { easyTrustManager }, null);
    SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
    sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Scheme https = new Scheme("https", sf, 443);

    //SchemeRegistry sr = new SchemeRegistry();
    //sr.register(http);
    //sr.register(https);

    // create and initialize scheme registry
    //SchemeRegistry schemeRegistry = new SchemeRegistry();
    //schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    // create an HttpClient with the ThreadSafeClientConnManager.
    // This connection manager must be used if more than one thread will
    // be using the HttpClient.
    //ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(schemeRegistry);
    //cm.setMaxTotalConnections(1);

    DefaultHttpClient client = new DefaultHttpClient();

    client.getConnectionManager().getSchemeRegistry().register(https);

    HttpPost post = new HttpPost(url);

    StringEntity postEntity = new StringEntity(requestXml, "ISO-8859-1");
    postEntity.setContentType("text/xml; charset=\"ISO-8859-1\"");
    post.addHeader("SOAPAction", "\"\"");
    post.setEntity(postEntity);

    long start = System.currentTimeMillis();

    client.getCredentialsProvider().setCredentials(new AuthScope(null, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(username, password));

    BasicHttpContext localcontext = new BasicHttpContext();

    // Generate BASIC scheme object and stick it to the local
    // execution context
    BasicScheme basicAuth = new BasicScheme();
    localcontext.setAttribute("preemptive-auth", basicAuth);

    // Add as the first request interceptor
    client.addRequestInterceptor(new PreemptiveAuth(), 0);

    HttpResponse httpResponse = client.execute(post, localcontext);
    HttpEntity responseEntity = httpResponse.getEntity();

    Response rsp = new Response();

    // set the status line and reason
    rsp.statusCode = httpResponse.getStatusLine().getStatusCode();
    rsp.statusLine = httpResponse.getStatusLine().getReasonPhrase();

    // get an input stream
    rsp.body = EntityUtils.toString(responseEntity);

    // When HttpClient instance is no longer needed,
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    client.getConnectionManager().shutdown();

    return rsp;
}

From source file:eu.cassandra.training.utils.APIUtilities.java

/**
 * This function is used to send the entity models to the Cassandra Server,
 * specifically on the connected user's Library.
 * /*from  ww  w .  j a  va  2  s. co  m*/
 * @param message
 *          The JSON schema of the entity.
 * @param suffix
 *          The library the model must be sent to.
 * @param id
 *          The id of the entity model in the Cassandra server.
 * @return a simple string of success or failure.
 * @throws IOException
 * @throws AuthenticationException
 * @throws NoSuchAlgorithmException
 */
public static String updateEntity(String message, String suffix, String id)
        throws IOException, AuthenticationException, NoSuchAlgorithmException {

    System.out.println(message);
    HttpPut httpput = new HttpPut(url + suffix + "/" + id);

    StringEntity entity = new StringEntity(message, "UTF-8");
    entity.setContentType("application/json");
    httpput.setEntity(entity);
    System.out.println("executing request: " + httpput.getRequestLine());

    HttpResponse response = httpclient.execute(httpput, localcontext);
    HttpEntity responseEntity = response.getEntity();
    String responseString = EntityUtils.toString(responseEntity, "UTF-8");
    System.out.println(responseString);

    return "Done";

}

From source file:org.openo.nfvo.monitor.umc.util.APIHttpClient.java

@SuppressWarnings({ "resource" })
public static String doPost2Str(String url, JSONObject json, String token) {
    DefaultHttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(url);
    String response = null;/*from  ww  w. jav  a  2  s .com*/
    try {
        if (null != json) {
            StringEntity s = new StringEntity(json.toString());
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json"); // set contentType
            post.setEntity(s);
        }
        if (!Global.isEmpty(token)) {
            post.addHeader("X-Auth-Token", token);
        }
        HttpResponse res = client.execute(post);
        if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK
                || res.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
            String result = EntityUtils.toString(res.getEntity());
            if (!Global.isEmpty(result)) {
                response = result;
            } else {
                response = null;
            }
        }
    } catch (Exception e) {
        logger.error("Exception", e);
    }
    return response;
}

From source file:test.java.ecplugins.weblogic.TestUtils.java

public static void setResourceAndWorkspace(String resourceName, String workspaceName, String pluginName)
        throws Exception {

    props = getProperties();/*from w  w  w  .  ja v a  2 s.  c om*/
    HttpClient httpClient = new DefaultHttpClient();
    JSONObject jo = new JSONObject();
    jo.put("projectName", pluginName);
    jo.put("resourceName", resourceName);
    jo.put("workspaceName", workspaceName);

    HttpPut httpPutRequest = new HttpPut("http://" + props.getProperty(StringConstants.COMMANDER_SERVER)
            + ":8000/rest/v1.0/projects/" + pluginName);

    String encoding = new String(
            org.apache.commons.codec.binary.Base64.encodeBase64(org.apache.commons.codec.binary.StringUtils
                    .getBytesUtf8(props.getProperty(StringConstants.COMMANDER_USER) + ":"
                            + props.getProperty(StringConstants.COMMANDER_PASSWORD))));
    StringEntity input = new StringEntity(jo.toString());

    input.setContentType("application/json");
    httpPutRequest.setEntity(input);
    httpPutRequest.setHeader("Authorization", "Basic " + encoding);
    HttpResponse httpResponse = httpClient.execute(httpPutRequest);

    if (httpResponse.getStatusLine().getStatusCode() >= 400) {
        throw new RuntimeException("Failed to set resource  " + resourceName + " to project " + pluginName);
    }
    System.out.println("Set the resource as " + resourceName + " and workspace as " + workspaceName
            + " successfully for " + pluginName);
}

From source file:eu.cassandra.training.utils.APIUtilities.java

/**
 * This function is used to send the entity models to the Cassandra Server,
 * specifically on the connected user's Library.
 * /*from  ww  w. j  a v a2  s . c om*/
 * @param message
 *          The JSON schema of the entity.
 * @param suffix
 *          The library the model must be sent to.
 * @return the id of the entity model provided by the server.
 * @throws IOException
 * @throws AuthenticationException
 * @throws NoSuchAlgorithmException
 */
public static String sendEntity(String message, String suffix)
        throws IOException, AuthenticationException, NoSuchAlgorithmException {

    System.out.println(message);
    HttpPost httppost = new HttpPost(url + suffix);

    StringEntity entity = new StringEntity(message, "UTF-8");
    entity.setContentType("application/json");
    httppost.setEntity(entity);
    System.out.println("executing request: " + httppost.getRequestLine());

    HttpResponse response = httpclient.execute(httppost, localcontext);
    HttpEntity responseEntity = response.getEntity();
    String responseString = EntityUtils.toString(responseEntity, "UTF-8");
    System.out.println(responseString);

    DBObject dbo = (DBObject) JSON.parse(responseString);

    DBObject dataObj = (DBObject) dbo.get("data");

    return dataObj.get("_id").toString();

}

From source file:test.java.ecplugins.weblogic.TestUtils.java

/**
 * callRunProcedure//from www  .j ava 2  s  . c om
 * 
 * @param jo
 * @return the jobId of the job launched by runProcedure
 */
public static String callRunProcedure(JSONObject jo) throws Exception {

    props = getProperties();
    HttpClient httpClient = new DefaultHttpClient();
    JSONObject result = null;

    try {
        String encoding = new String(
                org.apache.commons.codec.binary.Base64.encodeBase64(org.apache.commons.codec.binary.StringUtils
                        .getBytesUtf8(props.getProperty(StringConstants.COMMANDER_USER) + ":"
                                + props.getProperty(StringConstants.COMMANDER_PASSWORD))));

        HttpPost httpPostRequest = new HttpPost("http://" + props.getProperty(StringConstants.COMMANDER_SERVER)
                + ":8000/rest/v1.0/jobs?request=runProcedure");

        StringEntity input = new StringEntity(jo.toString());

        input.setContentType("application/json");
        httpPostRequest.setEntity(input);
        httpPostRequest.setHeader("Authorization", "Basic " + encoding);
        HttpResponse httpResponse = httpClient.execute(httpPostRequest);

        result = new JSONObject(EntityUtils.toString(httpResponse.getEntity()));
        return result.getString("jobId");

    } finally {
        httpClient.getConnectionManager().shutdown();
    }

}

From source file:core.RESTCalls.RESTPost.java

public static String httpPost(String urlStr, String data, String type) {

    String result = null;// w  ww .  ja v a  2 s.com

    if (type == null
            || (type != null && !type.equals("text/plain") && !type.equals("xml") && !type.equals("json"))) {

        System.err.println(
                "\n[ERROR] RESTPost: Unknown input type (" + type + ") in the Http RESTful post request.");

        return null;
    }

    else {

        try {

            HttpClient client = new DefaultHttpClient();

            HttpPost post = new HttpPost(urlStr);

            StringEntity input = new StringEntity(data);

            if (type.equals("text/plain"))
                input.setContentType("text/plain");

            else
                input.setContentType("application/" + type);

            post.setEntity(input);

            HttpResponse response = client.execute(post);

            if (response != null && response.getEntity() != null) {

                BufferedReader r = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

                StringBuilder total = new StringBuilder();

                String line = null;

                while ((line = r.readLine()) != null)
                    total.append(line + "\n");

                result = total.toString();
            }
        }

        catch (Exception ex) {

            ex.printStackTrace();
        }

        return result;
    }
}

From source file:com.networknt.light.server.handler.loader.FormLoader.java

private static void loadFormFile(String host, File file) {
    Scanner scan = null;//from w  w  w . jav a2s  .co m
    try {
        scan = new Scanner(file, Loader.encoding);
        // the content is only the data portion.
        String content = scan.useDelimiter("\\Z").next();
        // convert to map
        Map<String, Object> newMap = ServiceLocator.getInstance().getMapper().readValue(content,
                new TypeReference<HashMap<String, Object>>() {
                });
        String formId = (String) newMap.get("formId");
        Map<String, Object> oldMap = (Map<String, Object>) formMap.get(formId);
        boolean changed = false;
        if (oldMap == null) {
            // never loaded before.
            changed = true;
        } else {
            if (newMap.get("action") != null && !newMap.get("action").equals(oldMap.get("action"))) {
                changed = true;
            }
            if (!changed && newMap.get("schema") != null
                    && !newMap.get("schema").equals(oldMap.get("schema"))) {
                changed = true;
            }
            if (!changed && newMap.get("form") != null && !newMap.get("form").equals(oldMap.get("form"))) {
                changed = true;
            }
            if (!changed && newMap.get("modelData") != null
                    && !newMap.get("modelData").equals(oldMap.get("modelData"))) {
                changed = true;
            }
        }
        if (changed) {
            Map<String, Object> inputMap = new HashMap<String, Object>();
            inputMap.put("category", "form");
            inputMap.put("name", "impForm");
            inputMap.put("readOnly", false);

            Map<String, Object> data = new HashMap<String, Object>();
            data.put("content", content);
            inputMap.put("data", data);
            HttpPost httpPost = new HttpPost(host + "/api/rs");
            httpPost.addHeader("Authorization", "Bearer " + jwt);
            StringEntity input = new StringEntity(
                    ServiceLocator.getInstance().getMapper().writeValueAsString(inputMap));
            input.setContentType("application/json");
            httpPost.setEntity(input);
            CloseableHttpResponse response = httpclient.execute(httpPost);

            try {
                System.out.println("Form: " + file.getAbsolutePath() + " is loaded with status "
                        + response.getStatusLine());
                HttpEntity entity = response.getEntity();
                BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent()));
                String json = "";
                String line = "";
                while ((line = rd.readLine()) != null) {
                    json = json + line;
                }
                //System.out.println("json = " + json);
                EntityUtils.consume(entity);
            } finally {
                response.close();
            }
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } finally {
        if (scan != null)
            scan.close();
    }
}