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:net.acesinc.data.json.generator.log.HttpPostLogger.java

private void logEvent(String event) {
    try {/*from  ww w.j av  a 2s  .c  o m*/
        HttpPost request = new HttpPost(url);
        StringEntity input = new StringEntity(event);
        input.setContentType("application/json");
        request.setEntity(input);

        //            log.debug("executing request " + request);
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(request);
        } catch (IOException ex) {
            log.error("Error POSTing Event", ex);
        }
        if (response != null) {
            try {
                //                    log.debug("----------------------------------------");
                //                    log.debug(response.getStatusLine().toString());
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    //                        log.debug("Response content length: " + resEntity.getContentLength());
                }
                EntityUtils.consume(resEntity);
            } catch (IOException ioe) {
                //oh well
            } finally {
                try {
                    response.close();
                } catch (IOException ex) {
                }
            }
        }
    } catch (Exception e) {

    }
}

From source file:ly.apps.android.rest.converters.impl.JacksonBodyConverter.java

@Override
public <T> HttpEntity toRequestBody(T object, String contentType) {
    Logger.d("JacksonBodyConverter.toRequestBody: object: " + object);
    try {/*from   w  w w  . jav  a 2  s  . c o  m*/
        String json = mapper.writeValueAsString(object);
        Logger.d("JacksonHttpFormValuesConverter.toRequestBody: json: " + json);
        StringEntity result = new StringEntity(json, "UTF-8");
        result.setContentType(contentType);
        Logger.d("JacksonBodyConverter.toRequestBody: result: " + result);
        return result;
    } catch (UnsupportedEncodingException e) {
        throw new SerializationException(e);
    } catch (JsonMappingException e) {
        throw new SerializationException(e);
    } catch (JsonGenerationException e) {
        throw new SerializationException(e);
    } catch (IOException e) {
        throw new SerializationException(e);
    }
}

From source file:com.dv.sharer.android.rest.RestHttpOperations.java

protected HttpPost getPOST(String urlStr, String data) throws IOException {
    HttpPost httppost = new HttpPost(urlStr);
    httppost.setHeader("Content-Type", "application/json");
    StringEntity entity = new StringEntity(data);
    entity.setContentType("application/json");
    httppost.addHeader("Accept", "application/json");
    httppost.setEntity(entity);/*  ww w. j  a  v  a  2 s.c  o  m*/
    return httppost;
}

From source file:org.openiot.integration.VirtualSensor.java

public void createAndRegister() throws IOException, InterruptedException {

    HttpClient client = HttpClientBuilder.create().build();
    String name = "FER" + virtualSensorID;

    WriteXMLFile xmlFile = new WriteXMLFile(name, virtualSensorPort, sensorParameters, sensorTypes);
    String virtualSensor = xmlFile.createXML();

    String url = "http://" + gsnAddress + "/vs/vsensor/" + name + "/create";
    HttpPost request = new HttpPost(url);
    StringEntity input = new StringEntity(virtualSensor);
    input.setContentType("text/xml");
    request.setEntity(input);/*from ww  w. j a  v a2  s  .co  m*/
    HttpResponse response = client.execute(request);
    StatusLine statusLine = response.getStatusLine();
    boolean result = statusLine.getStatusCode() == 200;

    EntityUtils.toString(response.getEntity());
    response.getEntity().getContent().close();

    WriteMetadataFile metaFile = new WriteMetadataFile(name, virtualSensorID, latitude, longitude,
            sensorParameters, lsmProperty, lsmUnit);
    String sensorInstance = metaFile.createMetadata();

    url = "http://" + gsnAddress + "/vs/vsensor/" + name + "/register";
    request = new HttpPost(url);
    input = new StringEntity(sensorInstance);

    input.setContentType("text/xml");
    request.setEntity(input);
    response = client.execute(request);
    statusLine = response.getStatusLine();
    result = statusLine.getStatusCode() == 200;
    EntityUtils.toString(response.getEntity());
    response.getEntity().getContent().close();
}

From source file:com.obomprogramador.dropbackend.TestCreateLogin.java

private int sendRequest(String url, String sentity) {
    int resultCode = -1;
    try {// ww w. j a  v  a2  s . co  m
        HttpHost target = new HttpHost("localhost", 8080, "http");
        HttpPost postRequest = new HttpPost(url);

        StringEntity input = new StringEntity(sentity);
        input.setContentType("application/json");
        postRequest.setEntity(input);

        logger.debug("### executing request to " + target);

        HttpResponse httpResponse = httpclient.execute(target, postRequest);
        HttpEntity entity = httpResponse.getEntity();

        logger.debug("### ----------------------------------------");
        logger.debug("### " + httpResponse.getStatusLine());
        Header[] headers = httpResponse.getAllHeaders();
        for (int i = 0; i < headers.length; i++) {
            logger.debug("### " + headers[i]);
        }
        logger.debug("### ----------------------------------------");

        if (entity != null) {
            logger.debug("### " + EntityUtils.toString(entity));
            resultCode = httpResponse.getStatusLine().getStatusCode();
        }

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

From source file:de.devbliss.apitester.factory.impl.EntityBuilder.java

/**
 * Builds an entity from a given raw payload. If the payload is a string, it is directly used as payload, and the
 * entity's content type is text/plain, otherwise, it is serialized to JSON and the content type is set to
 * application/json./*from w ww .  jav a  2s. c o  m*/
 * 
 * @param payload payload which must not be null
 * @return entity
 * @throws IOException
 */
public StringEntity buildEntity(Object payload) throws IOException {
    boolean payloadIsString = payload instanceof String;
    String payloadAsString;

    if (payloadIsString) {
        payloadAsString = (String) payload;
    } else {
        payloadAsString = gson.toJson(payload);
    }

    StringEntity entity = new StringEntity(payloadAsString, ENCODING);

    if (payloadIsString) {
        entity.setContentType(ContentType.TEXT_PLAIN.getMimeType());
    } else {
        entity.setContentType(ContentType.APPLICATION_JSON.getMimeType());
    }

    return entity;
}

From source file:com.github.jdye64.reportingtasks.AbstractDeviceRegistryReportingTask.java

protected void reportToDeviceRegistry(ReportingContext reportingContext, String uri, String jsonString) {

    String host = reportingContext.getProperty(DEVICE_REGISTRY_HOST).evaluateAttributeExpressions().getValue();
    String port = reportingContext.getProperty(DEVICE_REGISTRY_PORT).evaluateAttributeExpressions().getValue();

    try {/*from ww w.  j  av a2 s .  c o m*/

        String url = "http://" + host + ":" + port + uri;

        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost postRequest = new HttpPost(url);

        StringEntity input = new StringEntity(jsonString);
        input.setContentType("application/json");
        postRequest.setEntity(input);

        HttpResponse response = httpClient.execute(postRequest);

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

        String output;
        while ((output = br.readLine()) != null) {
            if (getLogger().isDebugEnabled()) {
                getLogger().debug("NiFi Device Registry Response: {}", new Object[] { output });
            }
        }

        //Closes the BufferedReader
        br.close();

    } catch (Exception ex) {
        getLogger().error("Error POSTing Workflow pressured connections to NiFi Device Registry {}:{}",
                new Object[] { host, port }, ex);
    }
}

From source file:org.apache.stratos.mock.iaas.client.rest.RestClient.java

/**
 * Handle http post request. Return String
 *
 * @param resourcePath    This should be REST endpoint
 * @param jsonParamString The json string which should be executed from the post request
 * @return The HttpResponse/* www  .j  av  a 2s  .  com*/
 * @throws Exception if any errors occur when executing the request
 */
public HttpResponse doPost(URI resourcePath, String jsonParamString) throws Exception {
    HttpPost postRequest = null;
    try {
        postRequest = new HttpPost(resourcePath);

        StringEntity input = new StringEntity(jsonParamString);
        input.setContentType("application/json");
        postRequest.setEntity(input);

        return httpClient.execute(postRequest, new HttpResponseHandler());
    } finally {
        releaseConnection(postRequest);
    }
}

From source file:org.apache.stratos.mock.iaas.client.rest.RestClient.java

public HttpResponse doPut(URI resourcePath, String jsonParamString) throws Exception {

    HttpPut putRequest = null;/*  ww w.ja v a 2 s.com*/
    try {
        putRequest = new HttpPut(resourcePath);

        StringEntity input = new StringEntity(jsonParamString);
        input.setContentType("application/json");
        putRequest.setEntity(input);

        return httpClient.execute(putRequest, new HttpResponseHandler());
    } finally {
        releaseConnection(putRequest);
    }
}

From source file:com.shmsoft.dmass.lotus.SolrConnector.java

protected void sendPostCommand(String point, String param) throws Exception {
    HttpClient httpClient = new DefaultHttpClient();

    HttpPost request = new HttpPost(point);
    StringEntity params = new StringEntity(param, HTTP.UTF_8);
    params.setContentType("text/xml");

    request.setEntity(params);/*from   w  w  w  .  j av  a  2 s  .  c  o  m*/

    HttpResponse response = httpClient.execute(request);
    response.getStatusLine().getStatusCode();
}