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.bigdata.rockstor.console.RockStorSender.java

private static HttpRequestBase buildHttpRequest(HttpReq req)
        throws UnsupportedEncodingException, URISyntaxException {

    HttpRequestBase request = null;/*  ww w .  j a v a 2  s.  c  o m*/
    if ("GET".equals(req.getMethod())) {
        request = new HttpGet();
    } else if ("PUT".equals(req.getMethod())) {
        request = new HttpPut();
        if (req.getBody() != null && req.getBody().length() > 0)
            ((HttpPut) request).setEntity(new StringEntity(req.getBody()));
    } else if ("DELETE".equals(req.getMethod())) {
        request = new HttpDelete();
    } else if ("HEAD".equals(req.getMethod())) {
        request = new HttpHead();
    } else {
        throw new NullPointerException("Unknown HTTP Method : " + req.getMethod());
    }

    request.setURI(new URI(req.getUrl()));

    if (req.getHead() != null) {
        for (Map.Entry<String, String> e : req.getHead().entrySet()) {
            if ("PUT".equals(req.getMethod()) && e.getKey().equals("Content-Length"))
                continue;
            request.setHeader(e.getKey(), e.getValue());
        }
    }

    return request;
}

From source file:password.pwm.ws.client.rest.RestClientHelper.java

public static String makeOutboundRestWSCall(final PwmApplication pwmApplication, final Locale locale,
        final String url, final String jsonRequestBody)
        throws PwmOperationalException, PwmUnrecoverableException {
    final HttpPost httpPost = new HttpPost(url);
    httpPost.setHeader("Accept", PwmConstants.AcceptValue.json.getHeaderValue());
    if (locale != null) {
        httpPost.setHeader("Accept-Locale", locale.toString());
    }//  w w w .  ja  v a2  s .c om
    httpPost.setHeader("Content-Type", PwmConstants.ContentTypeValue.json.getHeaderValue());
    final HttpResponse httpResponse;
    try {
        final StringEntity stringEntity = new StringEntity(jsonRequestBody);
        stringEntity.setContentType(PwmConstants.AcceptValue.json.getHeaderValue());
        httpPost.setEntity(stringEntity);
        LOGGER.debug("beginning external rest call to: " + httpPost.toString() + ", body: " + jsonRequestBody);
        httpResponse = PwmHttpClient.getHttpClient(pwmApplication.getConfig()).execute(httpPost);
        final String responseBody = EntityUtils.toString(httpResponse.getEntity());
        LOGGER.trace("external rest call returned: " + httpResponse.getStatusLine().toString() + ", body: "
                + responseBody);
        if (httpResponse.getStatusLine().getStatusCode() != 200) {
            final String errorMsg = "received non-200 response code ("
                    + httpResponse.getStatusLine().getStatusCode() + ") when executing web-service";
            LOGGER.error(errorMsg);
            throw new PwmOperationalException(new ErrorInformation(PwmError.ERROR_UNKNOWN, errorMsg));
        }
        return responseBody;
    } catch (IOException e) {
        final String errorMsg = "http response error while executing external rest call, error: "
                + e.getMessage();
        LOGGER.error(errorMsg);
        throw new PwmOperationalException(new ErrorInformation(PwmError.ERROR_UNKNOWN, errorMsg), e);
    }
}

From source file:hobbyshare.testclient.RestService_TestClient.java

public void test_Login() {
    HttpClient httpClient = HttpClientBuilder.create().build();

    JSONObject loginAttempt = new JSONObject();
    loginAttempt.put("password", "1234");
    loginAttempt.put("userName", "77_username");

    try {/*ww w  . j av a  2  s  .c  om*/
        HttpPost request = new HttpPost("http://localhost:8095/login");
        StringEntity params = new StringEntity(loginAttempt.toString());
        request.addHeader("content-type", "application/json");
        request.setEntity(params);
        HttpResponse response = httpClient.execute(request);

        System.out.println("---Testing Login----");
        System.out.println(response.toString());
        HttpEntity entity = response.getEntity();
        String responseString = EntityUtils.toString(entity, "UTF-8");
        System.out.println(responseString);
        System.out.println("----End of login Test----");
    } catch (Exception ex) {
        // handle exception here
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

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

private void assertResponse(int port, String path) throws Exception {
    final String url = String.format("http://localhost:%s/%s", port, path);
    final Response response = Request.Post(url).body(new StringEntity(TEST_MESSAGE)).connectTimeout(1000)
            .execute();//from  w ww.ja  va2 s. c  om
    assertThat(response.returnContent().asString(), equalTo(TEST_MESSAGE));

}

From source file:WSpatern.LoginWS.java

public void getLoginAuth(String user, String password) {
    try {//from   w  w w .j  a  v a2  s. c om
        DefaultHttpClient client = new DefaultHttpClient();
        HttpPut putRequest = new HttpPut("https://documenta-dms.com/DMSWS/api/v1/login/");

        StringEntity input = new StringEntity("<user>\n" + "<username>" + user + "</username>\n" + "<password>"
                + password + "</password>\n" + "</user>");
        input.setContentType("application/xml");
        System.out.println("Out Put Of WS " + input);
        putRequest.setEntity(input);
        HttpResponse response = client.execute(putRequest);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String line = null;
        while ((line = rd.readLine()) != null) {

            System.out.println(line);
            if (!line.contains("<html>")) {
                parseXML(line);
            } else {
                valid = false;
            }

        }
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(LoginWS.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(LoginWS.class.getName()).log(Level.SEVERE, null, ex);
    }
}

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

@Test
public void testGetBody() throws UnsupportedEncodingException {
    HttpEntity entity = new StringEntity("This is a text");
    testGetBody(entity);// w w  w  . j a v  a 2 s .  co  m
}

From source file:com.noelportugal.amazonecho.SmartThings.java

public String setApp(String url, String body) {
    String output = "";
    try {//from   ww w  .  j a  v a2 s.co  m

        HttpPut httpPut = new HttpPut(url);
        httpPut.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
        httpPut.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + bearer);

        StringEntity xmlEntity = new StringEntity(body);
        httpPut.setEntity(xmlEntity);

        HttpResponse httpResponse = httpclient.execute(httpPut);
        httpResponse.getEntity();
        output = new BasicResponseHandler().handleResponse(httpResponse);

        if (xmlEntity != null) {
            EntityUtils.consume(xmlEntity);
        }

    } catch (Exception e) {
        System.err.println("setApp Error: " + e.getMessage());
    }

    return output;

}

From source file:service.StatisticsServerTest.java

public void testApp() throws UnsupportedEncodingException {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("http://194.28.132.219:8080/statsserver_archive/rest/");
    StringEntity entity = new StringEntity("{\"age\":\"38\",\"sex\":\"Male\",\"country\":\"Russia\"}");
    entity.setContentType("application/json");
    post.setEntity(entity);//from   www  .  j ava 2 s  .  co m
    try {
        HttpResponse response = client.execute(post);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String line = "";
        while ((line = rd.readLine()) != null) {
            System.out.println(line);
        }
    } catch (IOException e) {
        logger.error(e.getMessage());
    }
}

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

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

From source file:com.meschbach.psi.util.rest.JAXBEntityBuilder.java

public HttpEntity buildEntity() throws PSIException {
    try {//from www .  ja v a 2 s.c  o  m
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        JAXB.marshal(target, baos);
        return new StringEntity(baos.toString());
    } catch (Exception e) {
        throw new PSIException("Unable to marshall object " + target + "via JAXB", e);
    }
}