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) throws UnsupportedEncodingException 

Source Link

Usage

From source file:com.predic8.membrane.servlet.test.ReleaseConfigurationTest.java

@Test
public void testReachable() throws ClientProtocolException, IOException {
    String secret = "Web Services";
    HttpClient hc = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost(getBaseURL());
    post.setEntity(new StringEntity(secret));
    HttpResponse res = hc.execute(post);
    assertEquals(200, res.getStatusLine().getStatusCode());

    AssertUtils.assertContains(secret, EntityUtils.toString(res.getEntity()));
}

From source file:bit.changepurse.wdk.http.TestHTTPResponse.java

@Test
public void testLongBody() throws UnsupportedEncodingException {
    HttpEntity entity = new StringEntity(
            "This is a textThis is a textThis is a textThis is a textThis is a textThis is a textThis is a textThis is a text");
    testGetBody(entity);/*from ww w.  j a va 2s.com*/
}

From source file:com.restfiddle.handler.http.PostHandler.java

public RfResponseDTO process(RfRequestDTO rfRequestDTO) throws IOException {
    RfResponseDTO response = null;/*from  ww  w. j  a  v  a  2s  .  c o m*/
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(rfRequestDTO.getApiUrl());
    httpPost.addHeader("Content-Type", "application/json");
    httpPost.setEntity(new StringEntity(rfRequestDTO.getApiBody()));
    try {
        response = processHttpRequest(httpPost, httpclient);
    } finally {
        httpclient.close();
    }
    return response;
}

From source file:org.mule.module.http.functional.listener.HttpListenerExpressionFilterTestCase.java

private void sendRequestAndAssertResponse(boolean filterExpression, String expectedBody) throws IOException {
    Request request = Request.Post(String.format("http://localhost:%s", listenPort.getValue()))
            .body(new StringEntity(TEST_MESSAGE))
            .addHeader("filterExpression", Boolean.toString(filterExpression));

    HttpResponse response = request.execute().returnResponse();

    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
    assertThat(IOUtils.toString(response.getEntity().getContent()), equalTo(expectedBody));
}

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

public static void login(String host, String userId, String password) throws Exception {
    Map<String, Object> inputMap = new HashMap<String, Object>();
    inputMap.put("category", "user");
    inputMap.put("name", "signInUser");
    inputMap.put("readOnly", false);
    Map<String, Object> data = new HashMap<String, Object>();
    data.put("userIdEmail", userId);
    data.put("password", password);
    data.put("rememberMe", true);
    data.put("clientId", "example@Browser");
    inputMap.put("data", data);

    HttpPost httpPost = new HttpPost(host + "/api/rs");
    StringEntity input = new StringEntity(
            ServiceLocator.getInstance().getMapper().writeValueAsString(inputMap));
    input.setContentType("application/json");
    httpPost.setEntity(input);//from   w  ww.  j av  a2  s  .  c o m
    CloseableHttpResponse response = httpclient.execute(httpPost);

    try {

        //System.out.println(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);
        Map<String, Object> jsonMap = ServiceLocator.getInstance().getMapper().readValue(json,
                new TypeReference<HashMap<String, Object>>() {
                });
        jwt = (String) jsonMap.get("accessToken");
        EntityUtils.consume(entity);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        response.close();
    }
}

From source file:org.eclipse.lyo.testsuite.server.trsutils.SendUtil.java

/**
 * /*  ww  w  .jav a  2s.  c om*/
 * @param uri             resource uri for creation factory
 * @param httpClient      client used to post to the uri
 * @param httpContext     http context to use for the call
 * @param contentType     content type to be used in the creation 
 * @param content         content to be used in the creation
 * @throws SendException  if an error occurs in posting to the uri
 */
public static String createResource(String uri, HttpClient httpClient, HttpContext httpContext,
        String contentType, String content) throws SendException {
    String createdResourceUri = "";
    if (uri == null)
        throw new IllegalArgumentException(Messages.getServerString("send.util.uri.null")); //$NON-NLS-1$
    if (httpClient == null)
        throw new IllegalArgumentException(Messages.getServerString("send.util.httpclient.null")); //$NON-NLS-1$
    try {
        new URL(uri); // Make sure URL is valid

        HttpPost post = new HttpPost(uri);
        StringEntity entity = new StringEntity(content);
        post.setEntity(entity);
        post.setHeader(HttpConstants.ACCEPT, HttpConstants.CT_APPLICATION_RDF_XML);//$NON-NLS-1$
        post.addHeader(HttpConstants.CONTENT_TYPE, contentType);
        post.addHeader(HttpConstants.CACHE_CONTROL, "max-age=0"); //$NON-NLS-1$
        HttpResponse resp = httpClient.execute(post);

        try {
            if (resp.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) {
                HttpErrorHandler.responseToException(resp);
            }
            createdResourceUri = resp.getFirstHeader(HttpConstants.LOCATION).getValue();
            HttpResponseUtil.finalize(resp);
        } finally {
            try {
                if (entity != null) {
                    EntityUtils.consume(entity);
                }
            } catch (IOException e) {
                // ignore
            }
        }

    } catch (Exception e) {
        String uriLocation = Messages.getServerString("send.util.uri.unidentifiable"); //$NON-NLS-1$

        if (uri != null && !uri.isEmpty()) {
            uriLocation = uri;
        }
        throw new SendException(MessageFormat.format(Messages.getServerString("send.util.retrieve.error"), //$NON-NLS-1$
                uriLocation));
    }

    return createdResourceUri;
}

From source file:com.oracle.jes.samples.hellostorage.RegisterDevice.java

public String sendRecord(String m) {
    mode = false;/*  w ww . jav a  2s. com*/
    String out = null;

    //   DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpClient httpclient = HttpClientBuilder.create().build();

    HttpPost httppostreq;
    if (!mode) {

        httppostreq = new HttpPost("http://192.168.1.5:8080/pichrony/RegNewChrony");

    } else {
        httppostreq = new HttpPost("http://security.netmaxjava.com/phlogin");

    }

    StringEntity se = null;

    try {
        se = new StringEntity(m);
    } catch (UnsupportedEncodingException ex) {
        //Logger.getLogger(RegisterDevice.class.getName()).log(Level.SEVERE, null, ex);
    }

    //   se.setContentType("application/json;");

    httppostreq.setEntity(se);

    try {
        HttpResponse respo = httpclient.execute(httppostreq);
        if (respo != null) {
            out = "";
            InputStream inputstream = respo.getEntity().getContent();
            out = convertStreamToString(inputstream);

        } else {

        }
    } catch (ClientProtocolException e) {

    } catch (IOException | IllegalStateException e) {
    }
    return out;
}

From source file:com.appdynamics.openstack.nova.RestClient.java

static String doPost(String url, String entity, String token) throws Exception {
    HttpClient httpClient = httpClientWithTrustManager();
    StringEntity strEntity = new StringEntity(entity);
    strEntity.setContentType(jsonContentType);

    HttpPost post = new HttpPost(url);
    post.addHeader("accept", xmlContentType);
    post.setEntity(strEntity);// w ww .j  av  a 2  s  . co  m

    if (token != null) {
        post.addHeader("X-Auth-Token", token);
    }

    HttpResponse response = httpClient.execute(post);

    return getResponseString(httpClient, response);

}

From source file:com.ibm.iot.iotspark.IoTPrediction.java

/**
 * Makes ReST call to the Predictive Analytics service with the given payload and responds with the predicted score.
 * /*  w  w w . j  av a  2 s  .co m*/
 * @param pURL
 * @param payload
 * @return
 * @throws ClientProtocolException
 * @throws IOException
 */
public static java.lang.String post(java.lang.String pURL, java.lang.String payload)
        throws ClientProtocolException, IOException {

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(pURL);
    StringEntity input = new StringEntity(payload);
    input.setContentType("application/json");
    post.setEntity(input);

    HttpResponse response = client.execute(post);

    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    StringBuilder out = new StringBuilder();
    java.lang.String line;
    while ((line = rd.readLine()) != null) {
        //    System.out.println(line);
        out.append(line);
    }

    System.out.println(out.toString()); //Prints the string content read from input stream
    rd.close();
    return out.toString();
}

From source file:com.betfair.testing.utils.cougar.manager.CougarTestDAO.java

public org.apache.http.HttpResponse executeHttpMethodBaseCall(HttpUriRequest method) {
    // TODO Auto-generated method stub
    methods.add(method);//from   www . j  av a2  s .co m
    final BasicHttpResponse response = new BasicHttpResponse(
            new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, ""));
    try {
        response.setEntity(new StringEntity("test"));
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
    return response;
}