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

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

Introduction

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

Prototype

public StringEntity(String str, Charset charset) 

Source Link

Usage

From source file:org.megam.api.http.TransportMachinery.java

public static TransportResponse post(TransportTools nuts) throws ClientProtocolException, IOException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(nuts.urlString());
    System.out.println("NUTS" + nuts.toString());
    if (nuts.headers() != null) {
        for (Map.Entry<String, String> headerEntry : nuts.headers().entrySet()) {
            httppost.addHeader(headerEntry.getKey(), headerEntry.getValue());
        }/* www . ja  v  a2s .c  om*/
    }
    if (nuts.fileEntity() != null) {
        httppost.setEntity(nuts.fileEntity());
    }
    if (nuts.pairs() != null && (nuts.contentType() == null)) {
        httppost.setEntity(new UrlEncodedFormEntity(nuts.pairs()));
    }

    if (nuts.contentType() != null) {
        httppost.setEntity(new StringEntity(nuts.contentString(), nuts.contentType()));
    }
    TransportResponse transportResp = null;
    System.out.println(httppost.toString());
    try {
        HttpResponse httpResp = httpclient.execute(httppost);
        transportResp = new TransportResponse(httpResp.getStatusLine(), httpResp.getEntity(),
                httpResp.getLocale());
    } finally {
        httppost.releaseConnection();
    }
    return transportResp;

}

From source file:gertjvr.slacknotifier.SlackApiProcessor.java

public void sendNotification(String url, SlackNotificationMessage notification) throws IOException {
    String content = new Gson().toJson(notification);
    logger.debug(String.format("sendNotification: %s", content));

    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(url);

    httpPost.setEntity(new StringEntity(content, ContentType.APPLICATION_JSON));
    CloseableHttpResponse response = httpClient.execute(httpPost);

    try {//  w  ww. j  a va2  s. c o  m
        HttpEntity entity = response.getEntity();
        EntityUtils.consume(entity);
    } catch (Exception ex) {
        logger.error(String.format("sendNotification %s", ex.getMessage()), ex);
    } finally {
        response.close();
    }
}

From source file:azureml_besapp.AzureML_BESApp.java

/**
 * Call REST API to submit job to Azure ML for batch predictions
 * @return response from the REST API/*from   w w w  . j a v  a2 s . co m*/
 */
public static String besHttpPost() {

    HttpPost post;
    HttpClient client;
    StringEntity entity;

    try {
        // create HttpPost and HttpClient object
        post = new HttpPost(apiurl);
        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 " + apikey));
        post.setEntity(entity);

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

        jobId = EntityUtils.toString(authResponse.getEntity()).replaceAll("\"", "");

        return jobId;

    } catch (Exception e) {

        return e.toString();
    }

}

From source file:com.atomiton.watermanagement.ngo.util.HttpRequestResponseHandler.java

public static void sendPut(String serverURL, String postBody) throws Exception {

    CloseableHttpClient client = HttpClients.createDefault();
    HttpPut post = new HttpPut(serverURL);

    StringEntity entity = new StringEntity(postBody, "UTF-8");

    post.setEntity(entity);/*from   w ww.  j a  v  a  2  s  .  c  om*/

    HttpResponse response = client.execute(post);
    // System.out.println("\nSending 'PUT' request to URL : " + serverURL);

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

    StringBuffer result = new StringBuffer();
    String line = "";
    while ((line = rd.readLine()) != null) {
        result.append(line);
    }
    client.close();
    // System.out.println(result.toString());
}

From source file:com.currencyfair.minfraud.MinFraudImplTest.java

@Test
public void testRiskScoreResponseIsExtractedFromValidHttpResponse() throws Exception {
    StringEntity responseEntity = new StringEntity(VALID_RESPONSE, ContentType.TEXT_PLAIN);
    HttpMethodFactory methodFactory = expectCreateHttpPost();
    CloseableHttpResponse httpResponse = EasyMock.createMock(CloseableHttpResponse.class);
    expectHttpResponse(httpResponse, 200, responseEntity);
    expectClose(httpResponse, null);/*from   w w w  . ja v  a2 s .  co m*/
    HttpClient client = expectHttpInvocation(httpResponse);
    EasyMock.replay(httpResponse);
    minFraudImpl.setHttpClient(client);
    minFraudImpl.setMethodFactory(methodFactory);
    minFraudImpl.setEndpoint(ENDPOINT);
    RiskScoreResponse response = minFraudImpl.calculateRisk(newRiskScoreRequest());
    Assert.assertNotNull(response);
    Assert.assertEquals(new BigDecimal("23.2"), response.getRiskScore());
    Assert.assertTrue(response.getGeoIpDetails().isCountryMatch());
    Assert.assertFalse(response.getGeoIpDetails().isHighRiskCountry());
    Assert.assertEquals("IE", response.getGeoIpDetails().getIpCountryCode());
    Assert.assertEquals(Integer.valueOf(48), response.getGeoIpDetails().getDistance());
    EasyMock.verify(httpResponse);
}

From source file:org.camunda.connect.httpclient.TestResponse.java

public TestResponse payload(String payload, ContentType contentType) {
    if (payload != null) {
        setEntity(new StringEntity(payload, contentType));
    } else {//  w  w  w. j  a  va  2 s  .c o m
        setEntity(null);
    }
    return this;
}

From source file:com.yanzhenjie.andserver.sample.response.RequestLoginHandler.java

@Override
public void handle(HttpRequest request, HttpResponse response, HttpContext context)
        throws HttpException, IOException {
    Map<String, String> params = HttpRequestParser.parse(request);

    Log.i("AndServer", "Params: " + params.toString());

    String userName = params.get("username");
    String password = params.get("password");

    if ("123".equals(userName) && "123".equals(password)) {
        StringEntity stringEntity = new StringEntity("Login Succeed", "utf-8");
        response.setEntity(stringEntity);
    } else {//from www  . j  a  v  a 2 s.com
        StringEntity stringEntity = new StringEntity("Login Failed", "utf-8");
        response.setEntity(stringEntity);
    }
}

From source file:com.autonomy.nonaci.indexing.impl.PostDataImpl.java

public PostDataImpl(final String string, final String charset) {
    try {/* w w w  . j  a v a 2  s .  c om*/
        httpEntity = new StringEntity(string, StringUtils.isBlank(charset) ? "UTF-8" : charset);
    } catch (final UnsupportedCharsetException uce) {
        throw new IndexingException("Unsupported charset specified, " + charset, uce);
    }
}

From source file:de.intevation.irix.PrintClient.java

/** Obtains a Report from mapfish-print service.
 *
 * @param printUrl The url to send the request to.
 * @param json The json spec for the print request.
 * @param timeout the timeout for the httpconnection.
 *
 * @return byte[] with the report./* w ww.ja va  2 s .  com*/
 *
 * @throws IOException if communication with print service failed.
 * @throws PrintException if the print job failed.
 */
public static byte[] getReport(String printUrl, String json, int timeout) throws IOException, PrintException {

    RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout).build();

    CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(config).build();

    HttpEntity entity = new StringEntity(json,
            ContentType.create("application/json", Charset.forName("UTF-8")));

    HttpPost post = new HttpPost(printUrl);
    post.setEntity(entity);
    CloseableHttpResponse resp = client.execute(post);

    StatusLine status = resp.getStatusLine();

    byte[] retval = null;
    try {
        HttpEntity respEnt = resp.getEntity();
        InputStream in = respEnt.getContent();
        if (in != null) {
            try {
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                byte[] buf = new byte[BYTE_ARRAY_SIZE];
                int r;
                while ((r = in.read(buf)) >= 0) {
                    out.write(buf, 0, r);
                }
                retval = out.toByteArray();
            } finally {
                in.close();
                EntityUtils.consume(respEnt);
            }
        }
    } finally {
        resp.close();
    }

    if (status.getStatusCode() < HttpURLConnection.HTTP_OK
            || status.getStatusCode() >= HttpURLConnection.HTTP_MULT_CHOICE) {
        if (retval != null) {
            throw new PrintException(new String(retval));
        } else {
            throw new PrintException("Communication with print service '" + printUrl + "' failed."
                    + "\nNo response from print service.");
        }
    }
    return retval;
}