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.mondora.chargify.controller.ChargifyAdapter.java

public Customer create(Customer customer) throws ChargifyException {
    String xml = toXml(customer);
    HttpPost method = new HttpPost("/customers.xml");
    try {//from   w w  w  . j a  v a 2  s . co m
        StringEntity entity = new StringEntity(xml);
        entity.setContentEncoding(charset);
        entity.setContentType(contentType);
        method.setEntity(entity);
        if (logger.isTraceEnabled()) {
            logger.trace("createCustomer " + xml);
        }
        HttpResponse response = executeHttpMethod(method);
        handleResponseCode(response, method);
        return (Customer) parse(Customer.class, response, method);
    } catch (NotFoundException nfe) {
        throw nfe;
    } catch (ChargifyException ce) {
        throw ce;
    } catch (Exception e) {
        throw new ChargifyException(e);
    }
}

From source file:com.mondora.chargify.controller.ChargifyAdapter.java

protected Subscription createSubscription(String xml) throws ChargifyException {
    HttpPost method = new HttpPost("/subscriptions.xml");
    try {//from   ww  w  . j  av a 2  s .  c o  m
        StringEntity entity = new StringEntity(xml);
        entity.setContentEncoding(charset);
        entity.setContentType(contentType);
        method.setEntity(entity);
        if (logger.isTraceEnabled()) {
            logger.trace("createSubscription " + xml);
        }

        HttpResponse response = executeHttpMethod(method);
        handleResponseCode(response, method);
        return (Subscription) parse(Subscription.class, response, method);
    } catch (NotFoundException nfe) {
        return null;
    } catch (ChargifyException ce) {
        throw ce;
    } catch (Exception e) {
        throw new ChargifyException(e);
    }
}

From source file:org.lightcouch.CouchDbClientBase.java

/**
 * Sets a JSON String as a request entity.
 * @param httpRequest The request to set entity.
 * @param json The JSON String to set.//ww w .j a va2s  .co m
 */
protected void setEntity(HttpEntityEnclosingRequestBase httpRequest, String json) {
    try {
        StringEntity entity = new StringEntity(json, "UTF-8");
        entity.setContentType("application/json");
        httpRequest.setEntity(entity);
    } catch (UnsupportedEncodingException e) {
        log.error("Error setting request data. " + e.getMessage());
        throw new IllegalArgumentException(e);
    }
}

From source file:com.mozilla.simplepush.simplepushdemoapp.MainActivity.java

/** Send the registration id to the Push Server.
 *
 * Prior versions used a websocket based protocol to exchange this information. This
 * meant that android libraries had to bring in a websocket protocol dependency (see previous
 * versions of this code). This requirement was removed.
 *
 * @param regid GCM Registration ID//  w w w . j a  v a2s  .c o m
 */
private void sendRegistrationIdToBackend(final String regid) {
    String target = getTarget();
    Log.i(TAG, "Sending out Regid " + regid + " to " + target);
    JSONObject msg = new JSONObject();
    try {
        JSONObject token = new JSONObject();
        msg.put("type", "gcm");
        msg.put("channelID", CHANNEL_ID);
        token.put("token", regid);
        msg.put("data", token);
    } catch (JSONException x) {
        this.err("Could not send registration " + x.toString());
        return;
    }
    HttpPost req = new HttpPost(target);
    try {
        StringEntity body = new StringEntity(msg.toString());
        body.setContentType("application/json");
        body.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "text/plain; charset=UTF-8"));
        req.setEntity(body);
    } catch (UnsupportedEncodingException x) {
        this.err("Could not format registration message " + x.toString());
        return;
    }
    try {
        DefaultHttpClient client = new DefaultHttpClient();
        HttpResponse resp = client.execute(req);
        int code = resp.getStatusLine().getStatusCode();
        if (code < 200 || code > 299) {
            this.err("Server failed to accept message " + EntityUtils.toString(resp.getEntity()));
            return;
        }
        try {
            JSONObject reply = new JSONObject(new JSONTokener(EntityUtils.toString(resp.getEntity())));
            if (!this.CHANNEL_ID.equals(reply.getString("channelID"))) {
                this.err("Recieved inappropriate registration info: " + resp.getEntity().toString());
                return;
            }
            this.PushEndpoint = reply.getString("endpoint");
            this.UserAgentID = reply.getString("uaid");
            this.SharedSecret = reply.getString("secret");
        } catch (JSONException x) {
            this.err("Could not parse registration info " + x.toString());
        }
    } catch (IOException x) {
        this.err("Could not send registration " + x.toString());
    }
}

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

private static String verifyAnswer(String answer, JSONObject factor, String stateToken, String factorType)
        throws JSONException, ClientProtocolException, IOException {

    String sessionToken = null;/*w w w.  java  2s. c o  m*/

    JSONObject profile = new JSONObject();
    String verifyPoint = factor.getJSONObject("_links").getJSONObject("verify").getString("href");

    profile.put("stateToken", stateToken);

    JSONObject jsonObjResponse = null;

    //if (factorType.equals("question")) {

    if (answer != null && answer != "") {
        profile.put("answer", answer);
    }

    //create post request
    CloseableHttpResponse responseAuthenticate = null;
    CloseableHttpClient httpClient = HttpClients.createDefault();

    HttpPost httpost = new HttpPost(verifyPoint);
    httpost.addHeader("Accept", "application/json");
    httpost.addHeader("Content-Type", "application/json");
    httpost.addHeader("Cache-Control", "no-cache");

    StringEntity entity = new StringEntity(profile.toString(), StandardCharsets.UTF_8);
    entity.setContentType("application/json");
    httpost.setEntity(entity);
    responseAuthenticate = httpClient.execute(httpost);

    BufferedReader br = new BufferedReader(
            new InputStreamReader((responseAuthenticate.getEntity().getContent())));

    String outputAuthenticate = br.readLine();
    jsonObjResponse = new JSONObject(outputAuthenticate);

    if (jsonObjResponse.has("errorCode")) {
        String errorSummary = jsonObjResponse.getString("errorSummary");
        System.out.println(errorSummary);
        System.out.println("Please try again");
        if (factorType.equals("question")) {
            questionFactor(factor, stateToken);
        }

        if (factorType.equals("token:software:totp")) {
            totpFactor(factor, stateToken);
        }
    }
    //}

    if (jsonObjResponse != null && jsonObjResponse.has("sessionToken"))
        sessionToken = jsonObjResponse.getString("sessionToken");

    String pushResult = null;
    if (factorType.equals("push")) {
        if (jsonObjResponse.has("_links")) {
            JSONObject linksObj = jsonObjResponse.getJSONObject("_links");

            //JSONObject pollLink = links.getJSONObject("poll");
            JSONArray names = linksObj.names();
            JSONArray links = linksObj.toJSONArray(names);
            String pollUrl = "";
            for (int i = 0; i < links.length(); i++) {
                JSONObject link = links.getJSONObject(i);
                String linkName = link.getString("name");
                if (linkName.equals("poll")) {
                    pollUrl = link.getString("href");
                    break;
                    //System.out.println("[ " + (i+1) + " ] :" + factorType );
                }
            }

            while (pushResult == null || pushResult.equals("WAITING")) {
                pushResult = null;
                CloseableHttpResponse responsePush = null;
                httpClient = HttpClients.createDefault();

                HttpPost pollReq = new HttpPost(pollUrl);
                pollReq.addHeader("Accept", "application/json");
                pollReq.addHeader("Content-Type", "application/json");
                pollReq.addHeader("Cache-Control", "no-cache");

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

                responsePush = httpClient.execute(pollReq);

                br = new BufferedReader(new InputStreamReader((responsePush.getEntity().getContent())));

                String outputTransaction = br.readLine();
                JSONObject jsonTransaction = new JSONObject(outputTransaction);

                if (jsonTransaction.has("factorResult")) {
                    pushResult = jsonTransaction.getString("factorResult");
                }

                if (pushResult == null && jsonTransaction.has("status")) {
                    pushResult = jsonTransaction.getString("status");
                }

                System.out.println("Waiting for you to approve the Okta push notification on your device...");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException iex) {

                }

                //if(pushResult.equals("SUCCESS")) {
                if (jsonTransaction.has("sessionToken")) {
                    sessionToken = jsonTransaction.getString("sessionToken");
                }
                //}
                /*
                if(pushResult.equals("TIMEOUT")) {
                sessionToken = "timeout";
                }
                */
            }
        }

    }

    if (sessionToken != null)
        return sessionToken;
    else
        return pushResult;
}

From source file:org.exfio.weave.storage.StorageContext.java

public Double put(URI location, WeaveBasicObject wbo) throws WeaveException {
    Log.getInstance().debug("put()");

    Double modified = null;//  w w w  .ja v a2s .com

    HttpPut put = new HttpPut(location);
    CloseableHttpResponse response = null;

    try {
        //Backwards compatible with android version of org.apache.http
        StringEntity entityPut = new StringEntity(encodeWeaveBasicObject(wbo));
        entityPut.setContentType("text/plain");
        entityPut.setContentEncoding("UTF-8");

        put.setEntity(entityPut);

        response = httpClient.execute(put);
        checkResponse(response);

        //parse request content to extract server modified time
        modified = parseModifiedResponse(EntityUtils.toString(response.getEntity()));

    } catch (IOException e) {
        throw new WeaveException(e);
    } catch (HttpException e) {
        throw new WeaveException(e);
    } catch (GeneralSecurityException e) {
        throw new WeaveException(e);
    } finally {
        closeResponse(response);
    }

    return modified;
}

From source file:TestHTTPSource.java

@Test
public void testSingleEvent() throws Exception {
    StringEntity input = new StringEntity("[{\"headers\" : {\"a\": \"b\"},\"body\":" + " \"random_body\"}]");
    input.setContentType("application/json");
    postRequest.setEntity(input);/*from   ww w. j a v  a 2  s  .  c om*/

    httpClient.execute(postRequest);
    Transaction tx = channel.getTransaction();
    tx.begin();
    Event e = channel.take();
    Assert.assertNotNull(e);
    Assert.assertEquals("b", e.getHeaders().get("a"));
    Assert.assertEquals("random_body", new String(e.getBody(), "UTF-8"));
    tx.commit();
    tx.close();
}

From source file:edu.isi.wings.portal.controllers.RunController.java

private void publishFile(String tstoreurl, String graphurl, String filepath) {
    try {//from  w w w.  ja  v  a  2  s .  c  o m
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPut putRequest = new HttpPut(tstoreurl + "?graph=" + graphurl);

        int timeoutSeconds = 5;
        int CONNECTION_TIMEOUT_MS = timeoutSeconds * 1000;
        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(CONNECTION_TIMEOUT_MS)
                .setConnectTimeout(CONNECTION_TIMEOUT_MS).setSocketTimeout(CONNECTION_TIMEOUT_MS).build();
        putRequest.setConfig(requestConfig);

        File file = new File(filepath);
        String rdfxml = FileUtils.readFileToString(file);
        if (rdfxml != null) {
            StringEntity input = new StringEntity(rdfxml);
            input.setContentType("application/rdf+xml");

            putRequest.setEntity(input);
            httpClient.execute(putRequest);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.evolveum.polygon.scim.ServiceAccessManager.java

/**
 * Used for login to the service. The data needed for this operation is
 * provided by the configuration.//  w  w w  .ja  v  a 2 s .  c om
 * 
 * @param configuration
 *            The instance of "ScimConnectorConfiguration" which holds all
 *            the provided configuration data.
 * 
 * @return a Map object carrying meta information about the login session.
 */
public void logIntoService(ScimConnectorConfiguration configuration) {

    HttpPost loginInstance = new HttpPost();

    Header authHeader = null;
    String loginAccessToken = null;
    String loginInstanceUrl = null;
    JSONObject jsonObject = null;
    String proxyUrl = configuration.getProxyUrl();
    LOGGER.ok("proxyUrl: {0}", proxyUrl);
    //   LOGGER.ok("Configuration: {0}", configuration);
    if (!"token".equalsIgnoreCase(configuration.getAuthentication())) {

        HttpClient httpClient;

        if (proxyUrl != null && !proxyUrl.isEmpty()) {

            HttpHost proxy = new HttpHost(proxyUrl, configuration.getProxyPortNumber());

            DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);

            httpClient = HttpClientBuilder.create().setRoutePlanner(routePlanner).build();

            LOGGER.ok("Proxy enabled: {0}:{1}", proxyUrl, configuration.getProxyPortNumber());
        } else {

            httpClient = HttpClientBuilder.create().build();

        }
        String loginURL = new StringBuilder(configuration.getLoginURL()).append(configuration.getService())
                .toString();

        GuardedString guardedPassword = configuration.getPassword();
        GuardedStringAccessor accessor = new GuardedStringAccessor();
        guardedPassword.access(accessor);

        String contentUri = new StringBuilder("&client_id=").append(configuration.getClientID())
                .append("&client_secret=").append(configuration.getClientSecret()).append("&username=")
                .append(configuration.getUserName()).append("&password=").append(accessor.getClearString())
                .toString();

        loginInstance = new HttpPost(loginURL);
        CloseableHttpResponse response = null;

        StringEntity bodyContent;
        String getResult = null;
        Integer statusCode = null;
        try {
            bodyContent = new StringEntity(contentUri);
            bodyContent.setContentType("application/x-www-form-urlencoded");
            loginInstance.setEntity(bodyContent);

            response = (CloseableHttpResponse) httpClient.execute(loginInstance);

            getResult = EntityUtils.toString(response.getEntity());

            statusCode = response.getStatusLine().getStatusCode();

            if (statusCode == 200) {

                LOGGER.info("Login Successful");

            } else {

                String[] loginUrlParts;
                String providerName = "";

                if (configuration.getLoginURL() != null && !configuration.getLoginURL().isEmpty()) {

                    loginUrlParts = configuration.getLoginURL().split("\\."); // e.g.
                    // https://login.salesforce.com

                } else {

                    loginUrlParts = configuration.getBaseUrl().split("\\."); // e.g.
                }
                // https://login.salesforce.com
                if (loginUrlParts.length >= 2) {
                    providerName = loginUrlParts[1];
                }

                if (!providerName.isEmpty()) {

                    StrategyFetcher fetcher = new StrategyFetcher();
                    HandlingStrategy strategy = fetcher.fetchStrategy(providerName);
                    strategy.handleInvalidStatus(" while loging into service", getResult, "loging into service",
                            statusCode);
                }

            }

            jsonObject = (JSONObject) new JSONTokener(getResult).nextValue();

            loginAccessToken = jsonObject.getString("access_token");
            loginInstanceUrl = jsonObject.getString("instance_url");

        } catch (UnsupportedEncodingException e) {
            LOGGER.error("Unsupported encoding: {0}. Occurrence in the process of login into the service",
                    e.getLocalizedMessage());
            LOGGER.info("Unsupported encoding: {0}. Occurrence in the process of login into the service", e);

            throw new ConnectorException(
                    "Unsupported encoding. Occurrence in the process of login into the service", e);
        }

        catch (ClientProtocolException e) {

            LOGGER.error(
                    "An protocol exception has occurred while processing the http response to the login request. Possible mismatch in interpretation of the HTTP specification: {0}",
                    e.getLocalizedMessage());
            LOGGER.info(
                    "An protocol exception has occurred while processing the http response to the login request. Possible mismatch in interpretation of the HTTP specification: {0}",
                    e);

            throw new ConnectionFailedException(
                    "An protocol exception has occurred while processing the http response to the login request. Possible mismatch in interpretation of the HTTP specification",
                    e);

        } catch (IOException ioException) {

            StringBuilder errorBuilder = new StringBuilder(
                    "An error occurred while processing the query http response to the login request. ");

            if ((ioException instanceof SocketTimeoutException
                    || ioException instanceof NoRouteToHostException)) {

                errorBuilder.insert(0, "The connection timed out. ");

                throw new OperationTimeoutException(errorBuilder.toString(), ioException);
            } else {

                LOGGER.error(
                        "An error occurred while processing the query http response to the login request : {0}",
                        ioException.getLocalizedMessage());
                LOGGER.info(
                        "An error occurred while processing the query http response to the login request : {0}",
                        ioException);
                throw new ConnectorIOException(errorBuilder.toString(), ioException);
            }
        } catch (JSONException jsonException) {

            LOGGER.error(
                    "An exception has occurred while setting the \"jsonObject\". Occurrence while processing the http response to the login request: {0}",
                    jsonException.getLocalizedMessage());
            LOGGER.info(
                    "An exception has occurred while setting the \"jsonObject\". Occurrence while processing the http response to the login request: {0}",
                    jsonException);
            throw new ConnectorException("An exception has occurred while setting the \"jsonObject\".",
                    jsonException);
        } finally {
            try {
                response.close();
            } catch (IOException e) {

                if ((e instanceof SocketTimeoutException || e instanceof NoRouteToHostException)) {

                    throw new OperationTimeoutException(
                            "The connection timed out while closing the http connection. Occurrence in the process of logging into the service",
                            e);
                } else {

                    LOGGER.error(
                            "An error has occurred while processing the http response and closing the http connection. Occurrence in the process of logging into the service: {0}",
                            e.getLocalizedMessage());

                    throw new ConnectorIOException(
                            "An error has occurred while processing the http response and closing the http connection. Occurrence in the process of logging into the service",
                            e);
                }

            }

        }
        authHeader = new BasicHeader("Authorization", "OAuth " + loginAccessToken);
    } else {
        loginInstanceUrl = configuration.getBaseUrl();

        GuardedString guardedToken = configuration.getToken();

        GuardedStringAccessor accessor = new GuardedStringAccessor();
        guardedToken.access(accessor);

        loginAccessToken = accessor.getClearString();

        authHeader = new BasicHeader("Authorization", "Bearer " + loginAccessToken);
    }
    String scimBaseUri = new StringBuilder(loginInstanceUrl).append(configuration.getEndpoint())
            .append(configuration.getVersion()).toString();

    this.baseUri = scimBaseUri;
    this.aHeader = authHeader;
    if (jsonObject != null) {
        this.loginJson = jsonObject;
    }

}

From source file:com.neu.bigdata.service.PredictionService.java

private String rrsHttpPost() {

    HttpPost post;/*  w  ww  .  j  av  a2s  . com*/
    HttpClient client;
    StringEntity entity;
    String response = "";

    try {
        // create HttpPost and HttpClient object
        post = new HttpPost(API_URL);
        client = HttpClientBuilder.create().build();

        // setup output message by copying JSON body into 
        // apache StringEntity object along with content type
        entity = new StringEntity(jsonBody, HTTP.UTF_8);
        entity.setContentEncoding(HTTP.UTF_8);
        entity.setContentType("text/json");

        // add HTTP headers
        post.setHeader("Accept", "text/json");
        post.setHeader("Accept-Charset", "UTF-8");

        // set Authorization header based on the API key
        post.setHeader("Authorization", ("Bearer " + API_KEY));
        post.setEntity(entity);

        // Call REST API and retrieve response content
        HttpResponse authResponse = client.execute(post);
        response = EntityUtils.toString(authResponse.getEntity());

        return response;

    } catch (Exception e) {

        return e.toString();
    }

}