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.n52.sor.client.Client.java

/**
 * @param request//from  www .  ja  va2s  .  c  o  m
 * @return
 * @throws UnsupportedEncodingException
 * @throws IOException
 * @throws HttpException
 */
private static XmlObject doSend(String request, String requestMethod)
        throws UnsupportedEncodingException, IOException {
    log.debug("Sending request (first 100 characters): {}",
            request.substring(0, Math.min(request.length(), 100)));

    PropertiesManager pm = PropertiesManager.getInstance();

    // create and set up HttpClient
    try (CloseableHttpClient client = HttpClientBuilder.create().build();) {

        HttpRequestBase method = null;
        if (requestMethod.equals(GET_METHOD)) {
            String sorURL = pm.getServiceEndpointGet();
            log.debug("Client connecting via GET to {}", sorURL);

            HttpGet get = new HttpGet(request);
            method = get;
        } else if (requestMethod.equals(POST_METHOD)) {
            String sorURL = pm.getServiceEndpointPost();
            log.debug("Client connecting via POST to {}", sorURL);
            HttpPost postMethod = new HttpPost(sorURL.toString());

            postMethod.setEntity(
                    new StringEntity(request, PropertiesManager.getInstance().getClientRequestContentType()));

            method = postMethod;
        } else
            throw new IllegalArgumentException("requestMethod not supported!");

        HttpResponse httpResponse = client.execute(method);
        XmlObject response = XmlObject.Factory.parse(httpResponse.getEntity().getContent());

        return response;
    } catch (XmlException e) {
        log.error("Error parsing response.", e);
    }
    return null;
}

From source file:com.neu.bigdata.service.PredictionService.java

private String rrsHttpPost() {

    HttpPost post;//  w  w  w.j  a  v  a 2  s  .  c  o  m
    HttpClient client;
    StringEntity entity;
    String response = "";

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

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

        return response;

    } catch (Exception e) {

        return e.toString();
    }

}

From source file:com.sepgil.ral.UpdateNodeTask.java

@Override
public HttpRequestBase getHttpRequest(String url) {
    HttpPost post = new HttpPost(url);

    try {/* w w  w  .  jav a 2  s  .c  o m*/
        StringEntity enity = new StringEntity(mNode.getJSON(), HTTP.UTF_8);
        post.setEntity(enity);
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return post;
}

From source file:org.elasticsearch.shell.command.HttpPutCommand.java

@SuppressWarnings("unused")
public HttpCommandResponse execute(String url, String body) throws IOException {
    HttpPut httpPut = new HttpPut(url);
    httpPut.setEntity(new StringEntity(body, ContentType.DEFAULT_TEXT));
    return new HttpCommandResponse(shellHttpClient.getHttpClient().execute(httpPut));
}

From source file:com.joken.notice.message.util.HttpRequestHandler.java

/**
 * ??post/*from   ww w  . j  av  a  2  s  .  co m*/
 * @Auther Hanzibin
 * @date 3:18:48 PM,Mar 11, 2016
 * @return String 
 */
public String sendPostRequest() {
    CloseableHttpResponse httpResponse = null;
    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
    connManager.setMaxTotal(300);
    connManager.setDefaultMaxPerRoute(20);
    if (requestConfig == null) {
        requestConfig = RequestConfig.custom().setConnectionRequestTimeout(10000)
                .setStaleConnectionCheckEnabled(true).setConnectTimeout(10000).setSocketTimeout(10000).build();
    }
    CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connManager)
            .setDefaultRequestConfig(requestConfig).build();

    HttpPost hp = new HttpPost(url);
    try {
        StringEntity entity = new StringEntity(postData, Charset.forName("UTF-8"));//?    
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        hp.setEntity(entity);
        httpResponse = httpClient.execute(hp);
        return EntityUtils.toString(httpResponse.getEntity());
    } catch (Throwable t) {
        t.printStackTrace();
        log.info("??Http" + postData.toString() + "");
    } finally {
        try {
            hp.releaseConnection();
        } catch (Exception e) {
        }
    }
    return null;
}

From source file:com.keydap.sparrow.auth.SparrowAuthenticator.java

@Override
public void authenticate(String baseUrl, CloseableHttpClient client) throws Exception {
    HttpPost post = new HttpPost(baseUrl + "/directLogin");
    String body = new Gson().toJson(authReq);
    StringEntity entity = new StringEntity(body, ContentType.APPLICATION_JSON);
    post.setEntity(entity);/*from  ww w.j  a  v a 2s.  c  o m*/

    HttpResponse resp = client.execute(post);
    StatusLine sl = resp.getStatusLine();

    if ((sl.getStatusCode() != 200) && (sl.getStatusCode() != 201)) {
        String msg = "Authentication failed [code: %d, reason: %s]";
        msg = String.format(msg, sl.getStatusCode(), sl.getReasonPhrase());
        LOG.warn(msg);
        throw new IllegalStateException(msg);
    }

    LOG.debug("Successfully authenticated");
    token = EntityUtils.toString(resp.getEntity());
}

From source file:org.elasticsearch.client.RankEvalIT.java

@Before
public void indexDocuments() throws IOException {
    StringEntity doc = new StringEntity("{\"text\":\"berlin\"}", ContentType.APPLICATION_JSON);
    client().performRequest("PUT", "/index/doc/1", Collections.emptyMap(), doc);
    doc = new StringEntity("{\"text\":\"amsterdam\"}", ContentType.APPLICATION_JSON);
    client().performRequest("PUT", "/index/doc/2", Collections.emptyMap(), doc);
    client().performRequest("PUT", "/index/doc/3", Collections.emptyMap(), doc);
    client().performRequest("PUT", "/index/doc/4", Collections.emptyMap(), doc);
    client().performRequest("PUT", "/index/doc/5", Collections.emptyMap(), doc);
    client().performRequest("PUT", "/index/doc/6", Collections.emptyMap(), doc);
    client().performRequest("POST", "/index/_refresh");

    // add another index to test basic multi index support
    client().performRequest("PUT", "/index2/doc/7", Collections.emptyMap(), doc);
    client().performRequest("POST", "/index2/_refresh");
}

From source file:org.elasticsearch.shell.command.HttpPostCommand.java

@SuppressWarnings("unused")
public HttpCommandResponse execute(String url, String body) throws IOException {
    HttpPost httpPut = new HttpPost(url);
    httpPut.setEntity(new StringEntity(body, ContentType.DEFAULT_TEXT));
    return new HttpCommandResponse(shellHttpClient.getHttpClient().execute(httpPut));
}

From source file:org.aicer.hibiscus.http.workers.HttpEntityEnclosingRequestWorker.java

/**
 * {@inheritDoc}/*from  w  w w .  ja  v a 2s.  c  o m*/
 */
@Override
public void prepare() throws HibiscusException {

    HttpEntityEnclosingRequestBase request = (HttpEntityEnclosingRequestBase) this.httpRequest;

    try {
        request.setURI(getURI());

        for (BasicNameValuePair header : httpClient.getRequestHeaders()) {
            request.addHeader(header.getName(), header.getValue());
        }

    } catch (URISyntaxException e1) {
        throw new HibiscusException(e1);
    }

    final String requestBody = httpClient.getRequestBody();
    final int contentLength = (null != requestBody) ? requestBody.length() : 0;

    if (contentLength > 0) {
        try {
            request.setEntity(new StringEntity(requestBody, httpClient.getEncoding()));
        } catch (UnsupportedEncodingException e2) {
            throw new HibiscusException("The encoding " + httpClient.getEncoding() + " is not supported", e2);
        }
    }
}

From source file:org.elasticsearch.smoketest.SmokeTestWatcherWithSecurityIT.java

@Before
public void startWatcher() throws Exception {
    StringEntity entity = new StringEntity("{ \"value\" : \"15\" }", ContentType.APPLICATION_JSON);
    assertOK(adminClient().performRequest("PUT", "my_test_index/doc/1",
            Collections.singletonMap("refresh", "true"), entity));

    // delete the watcher history to not clutter with entries from other test
    adminClient().performRequest("DELETE", ".watcher-history-*", Collections.emptyMap());

    // create one document in this index, so we can test in the YAML tests, that the index cannot be accessed
    Response resp = adminClient().performRequest("PUT", "/index_not_allowed_to_read/doc/1",
            Collections.emptyMap(), new StringEntity("{\"foo\":\"bar\"}", ContentType.APPLICATION_JSON));
    assertThat(resp.getStatusLine().getStatusCode(), is(201));

    assertBusy(() -> {//from  w  w w. j a va2s.  c o m
        try {
            Response statsResponse = adminClient().performRequest("GET", "_xpack/watcher/stats");
            ObjectPath objectPath = ObjectPath.createFromResponse(statsResponse);
            String state = objectPath.evaluate("stats.0.watcher_state");

            switch (state) {
            case "stopped":
                Response startResponse = adminClient().performRequest("POST", "_xpack/watcher/_start");
                assertOK(startResponse);
                String body = EntityUtils.toString(startResponse.getEntity());
                assertThat(body, containsString("\"acknowledged\":true"));
                break;
            case "stopping":
                throw new AssertionError("waiting until stopping state reached stopped state to start again");
            case "starting":
                throw new AssertionError("waiting until starting state reached started state");
            case "started":
                // all good here, we are done
                break;
            default:
                throw new AssertionError("unknown state[" + state + "]");
            }
        } catch (IOException e) {
            throw new AssertionError(e);
        }
    });

    assertBusy(() -> {
        for (String template : WatcherIndexTemplateRegistryField.TEMPLATE_NAMES) {
            assertOK(adminClient().performRequest("HEAD", "_template/" + template));
        }
    });
}