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

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

Introduction

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

Prototype

public void setContentEncoding(Header header) 

Source Link

Usage

From source file:se.berazy.api.client.PoSInvoiceClient.java

/**
 * Sends a POST request./*from   w w w .j av a 2s  . c  om*/
 * 
 * @param  object
 * @throws ClientProtocolException 
 * @throws IOException 
 */
<TRequest, TResponse> TResponse sendRequest(String url, JAXBElement<TRequest> requestObject,
        Class<TResponse> responseObject) throws IOException, ClientProtocolException {
    loadProperties();
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);
    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");

    String key = EncryptionUtils.hash((getIpAddress() + formatter.format(new Date()) + getAuthToken()));
    httpPost.addHeader("accept", "application/xml");
    httpPost.addHeader("customerNo", getCustomerNo().toString());
    httpPost.addHeader("key", key);

    try {
        String data = XmlUtils.serialize(requestObject);
        StringEntity stringEntity = new StringEntity(data);
        stringEntity.setContentType("application/xml");
        stringEntity.setContentEncoding("UTF-8");
        httpPost.setEntity(stringEntity);
        log.debug(String.format("XML request: ", data));
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream instream = entity.getContent();
            try {
                InputStream is = response.getEntity().getContent();
                return XmlUtils.deserialize(is, responseObject);
            } catch (IOException e) {
                throw e;
            } catch (RuntimeException e) {
                httpPost.abort();
                throw e;
            } finally {
                try {
                    instream.close();
                } catch (Exception e) {
                    log.warn("Cannot close response stream.", e);
                }
            }
        } else {
            throw new ClientProtocolException("Response contains no content");
        }
    } catch (JAXBException e) {
        throw new ClientProtocolException("Malformed XML", e);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:eu.vranckaert.worktime.web.json.JsonWebServiceImpl.java

@Override
public JsonResult webInvokePost(String baseUrl, String methodName, AuthorizationHeader authorizationHeader,
        Map<String, String> ampParams, JsonEntity jsonEntity, String... parameters)
        throws WebException, CommunicationException {
    String endpoint = baseUrl + methodName;

    if (parameters != null && parameters.length > 0) {
        for (Object param : parameters) {
            endpoint += "/" + param;
        }//w  w  w  . j a v  a 2s.c  om
    }

    endpoint = buildEndpointWithAmpParams(endpoint, ampParams);

    httpPost = new HttpPost(endpoint);
    httpPost.setHeader(new BasicHeader(HTTP.CONTENT_ENCODING, "utf-8"));
    httpPost.setHeader(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
    if (authorizationHeader != null) {
        httpPost.setHeader("Authorization", authorizationHeader.getContent());
    }

    if (jsonEntity != null) {
        String data = jsonEntity.toJSON();

        try {
            StringEntity entity = new StringEntity(data, "utf-8");
            entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            httpPost.setEntity(entity);
        } catch (UnsupportedEncodingException e) {
        }
    }

    HttpClient client = authorizationHeader == null ? getClient() : getNewClient();
    try {
        HttpResponse response = client.execute(httpPost);
        return handleHttpResponse(response);
    } catch (UnknownHostException e) {
        throw new CommunicationException(e);
    } catch (IOException e) {
        throw new CommunicationException(e);
    }
}

From source file:com.postmark.PostmarkMailSender.java

@Override
public void send(SimpleMailMessage message) throws MailException {

    HttpClient httpClient = new DefaultHttpClient();
    PostmarkResponse theResponse = new PostmarkResponse();

    try {//from w  w  w.  j a va  2s  .  c  om

        // Create post request to Postmark API endpoint
        HttpPost method = new HttpPost("http://api.postmarkapp.com/email");

        // Add standard headers required by Postmark
        method.addHeader("Accept", "application/json");
        method.addHeader("Content-Type", "application/json; charset=utf-8");
        method.addHeader("X-Postmark-Server-Token", serverToken);
        method.addHeader("User-Agent", "Postmark-Java");

        // Convert the message into JSON content
        String messageContents = UnicodeEscapeFilterWriter.escape(gson.toJson(message));
        logger.log(Level.FINER, "Message contents: " + messageContents);

        // Add JSON as payload to post request
        StringEntity payload = new StringEntity(messageContents);
        payload.setContentEncoding(HTTP.UTF_8);
        method.setEntity(payload);

        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        try {
            String response = httpClient.execute(method, responseHandler);
            logger.log(Level.FINER, "Message response: " + response);
            theResponse = gson.fromJson(response, PostmarkResponse.class);
            theResponse.status = PostmarkResponseStatus.SUCCESS;
        } catch (HttpResponseException hre) {
            switch (hre.getStatusCode()) {
            case 401:
            case 422:
                logger.log(Level.SEVERE, "There was a problem with the email: " + hre.getMessage());
                theResponse.setMessage(hre.getMessage());
                theResponse.status = PostmarkResponseStatus.USERERROR;
                throw new MailSendException("Postmark returned: " + theResponse);
            case 500:
                logger.log(Level.SEVERE, "There has been an error sending your email: " + hre.getMessage());
                theResponse.setMessage(hre.getMessage());
                theResponse.status = PostmarkResponseStatus.SERVERERROR;
                throw new MailSendException("Postmark returned: " + theResponse);
            default:
                logger.log(Level.SEVERE,
                        "There has been an unknow error sending your email: " + hre.getMessage());
                theResponse.status = PostmarkResponseStatus.UNKNOWN;
                theResponse.setMessage(hre.getMessage());
                throw new MailSendException("Postmark returned: " + theResponse);
            }
        }

    } catch (Exception e) {
        logger.log(Level.SEVERE, "There has been an error sending email: " + e.getMessage());
        throw new MailSendException("There has been an error sending email", e);

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

}

From source file:org.openhab.binding.plum.PlumActiveBinding.java

private String sendHttpCommand(String ip, String apiCall, Map<String, Object> args) throws Exception {

    HttpClient httpclient = PlumUtilities.getHttpClient();
    // Prepare a request object
    HttpPost httppost = new HttpPost("https://" + ip + ":8443/v2/" + apiCall);
    httppost.setHeader("User-Agent", "Plum/2.3.0 (iPhone; iOS 9.2.1; Scale/2.00)");
    httppost.setHeader("X-Plum-House-Access-Token", PlumUtilities.sha256(m_config.get("house_token")));
    httppost.setHeader("Content-type", "application/json");

    JSONObject json = new JSONObject();
    for (Entry<String, Object> kv : args.entrySet()) {
        json.put(kv.getKey(), kv.getValue());
    }//from   w w  w.ja  v a 2s.co m

    StringEntity se = new StringEntity(json.toString());
    se.setContentEncoding("UTF-8");

    httppost.setEntity(se);

    // Execute the request
    HttpResponse response = httpclient.execute(httppost);

    // Examine the response status
    logger.info("Plum HTTP Request to IP " + ip + " returned: " + response.getStatusLine());

    // Get hold of the response entity
    HttpEntity entity = response.getEntity();
    String responseString = null;
    if (entity != null) {
        responseString = EntityUtils.toString(entity, "UTF-8");
    }

    // If the response does not enclose an entity, there is no need
    // to worry about connection release
    if (entity != null) {
        httpclient.getConnectionManager().shutdown();
    }

    return responseString;
}

From source file:br.gov.frameworkdemoiselle.behave.integration.alm.ALMIntegration.java

public HttpResponse sendRequest(HttpClient client, String resource, String id, String xmlRequest)
        throws ClientProtocolException, IOException {
    String url = urlServer + "resources/" + projectAreaAlias + "/" + resource + "/" + id;

    log.debug(url);//from   www.  ja  v  a  2s  .  c  o  m

    HttpPut request = new HttpPut(url);
    request.addHeader("Content-Type", "application/xml; charset=" + ENCODING);
    request.addHeader("Encoding", ENCODING);

    HttpParams params = request.getParams();
    params.setParameter(ClientPNames.HANDLE_REDIRECTS, Boolean.FALSE);

    // Seta o encoding da mensagem XML
    ContentType ct = ContentType.create("text/xml", ENCODING);

    StringEntity se = new StringEntity(xmlRequest, ct);
    se.setContentType("text/xml");
    se.setContentEncoding(ENCODING);
    request.setEntity(se);

    log.debug(xmlRequest);

    return client.execute(request);
}

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

protected File createSimpleProject(String projectName) throws IOException {
    String url = "/project?asFolder";
    HttpPost post = new HttpPost(prefix + url);
    StringEntity entity = new StringEntity("{\"name\":\"" + projectName + "\"}");
    entity.setContentEncoding("UTF-8");
    entity.setContentType("application/json");
    post.setEntity(entity);//  ww w .j av  a  2  s .  c  o  m
    post.setHeader(defaultHeader);
    String response = this.simpleCall(post);
    return convertString2Obj(response, File.class);
}

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

public MeteredUsage componentCreateUsage(String sub, String comp, Integer quantity, String memo)
        throws ChargifyException {
    String xml = "<usage>" + "<id>" + AUTO_GENERATED + "</id>" + "<quantity type=\"integer\">"
            + Integer.toString(quantity) + "</quantity>" + "<memo>" + String.valueOf(memo) + "</memo>"
            + "</usage>";

    HttpPost method = new HttpPost("/subscriptions/" + sub + "/components/" + comp + "/usages.xml");
    try {//  w  w w . jav a  2s.c o m
        StringEntity entity = new StringEntity(xml);
        entity.setContentEncoding(charset);
        entity.setContentType(contentType);
        method.setEntity(entity);

        HttpResponse response = executeHttpMethod(method);
        handleResponseCode(response, method);
        return (MeteredUsage) parse(MeteredUsage.class, response, method);
    } catch (Exception e) {
        throw new ChargifyException(e);
    }
}

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  ww w  .j  a va2  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 w w w  .  jav  a  2  s.  c  om
        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:com.glodon.paas.document.api.AbstractDocumentAPITest.java

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