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:com.vaushell.treetasker.client.SimpleJsonClient.java

public <T> T post(Class<T> responseClass, Object objectToSend) throws IOException, E_BadResponseStatus {
    HttpPost request = new HttpPost(
            cleanURI(TT_Tools.convertNullStringToEmpty(resource) + TT_Tools.convertNullStringToEmpty(path)));

    StringEntity se = null;/*www  . j  a va2  s.  c om*/
    try {
        String sending = gson.toJson(objectToSend);
        System.out.println("[SENDING]");
        System.out.println(sending);
        se = new StringEntity(sending, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
    request.setHeader("Accept", "application/json");
    request.setHeader("Content-type", "application/json");
    request.setEntity(se);

    HttpResponse response = null;
    try {
        response = client.execute(request);
    } catch (ClientProtocolException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw e;
    }

    StatusLine statusLine = response.getStatusLine();

    if (statusLine.getStatusCode() / 100 != 2) // status code no success
    {
        throw new E_BadResponseStatus(statusLine.getStatusCode(), statusLine.getReasonPhrase());
    }

    try {
        BufferedReader buffReader = new BufferedReader(
                new InputStreamReader(response.getEntity().getContent()));

        try {
            StringBuilder builder = new StringBuilder();

            System.out.println("[RECEIVING]");
            String line = buffReader.readLine();
            while (line != null) {
                builder.append(line);
                System.out.println(line);
                line = buffReader.readLine();
            }

            buffReader.close();

            return gson.fromJson(builder.toString(), responseClass);
        } catch (JsonSyntaxException e) {
            throw new RuntimeException(e);
        } catch (JsonIOException e) {
            throw new RuntimeException(e);
        } catch (IllegalStateException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            buffReader.close();
        }
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    return null;
}

From source file:org.keycloak.client.registration.HttpUtil.java

InputStream doPost(String content, String contentType, Charset charset, String acceptType, String... path)
        throws ClientRegistrationException {
    try {//  w  ww.  ja v  a  2 s . co m
        HttpPost request = new HttpPost(getUrl(baseUri, path));

        request.setHeader(HttpHeaders.CONTENT_TYPE, contentType(contentType, charset));
        request.setHeader(HttpHeaders.ACCEPT, acceptType);
        request.setEntity(new StringEntity(content, charset));

        addAuth(request);

        HttpResponse response = httpClient.execute(request);
        InputStream responseStream = null;
        if (response.getEntity() != null) {
            responseStream = response.getEntity().getContent();
        }

        if (response.getStatusLine().getStatusCode() == 201) {
            return responseStream;
        } else {
            throw httpErrorException(response, responseStream);
        }
    } catch (IOException e) {
        throw new ClientRegistrationException("Failed to send request", e);
    }
}

From source file:com.braffdev.server.core.http.environment.operator.SendStatusOperator.java

/**
 * @param code/*from  w  ww  .j  a v a  2  s.c  o  m*/
 * @param args
 */
public void sendStatus(int code, String... args) {
    if (code != HttpStatus.SC_NO_CONTENT) {
        String text = this.statusMessageBuilder.build(code, args);
        StringEntity entity = new StringEntity(text, ContentType.TEXT_HTML);
        this.response.setEntity(entity);
    }
}

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

public void testResponseException() throws IOException {
    ProtocolVersion protocolVersion = new ProtocolVersion("http", 1, 1);
    StatusLine statusLine = new BasicStatusLine(protocolVersion, 500, "Internal Server Error");
    HttpResponse httpResponse = new BasicHttpResponse(statusLine);

    String responseBody = "{\"error\":{\"root_cause\": {}}}";
    boolean hasBody = getRandom().nextBoolean();
    if (hasBody) {
        HttpEntity entity;// w  w  w. j  a  va  2  s  .  c  o  m
        if (getRandom().nextBoolean()) {
            entity = new StringEntity(responseBody, ContentType.APPLICATION_JSON);
        } else {
            //test a non repeatable entity
            entity = new InputStreamEntity(
                    new ByteArrayInputStream(responseBody.getBytes(StandardCharsets.UTF_8)),
                    ContentType.APPLICATION_JSON);
        }
        httpResponse.setEntity(entity);
    }

    RequestLine requestLine = new BasicRequestLine("GET", "/", protocolVersion);
    HttpHost httpHost = new HttpHost("localhost", 9200);
    Response response = new Response(requestLine, httpHost, httpResponse);
    ResponseException responseException = new ResponseException(response);

    assertSame(response, responseException.getResponse());
    if (hasBody) {
        assertEquals(responseBody, EntityUtils.toString(responseException.getResponse().getEntity()));
    } else {
        assertNull(responseException.getResponse().getEntity());
    }

    String message = response.getRequestLine().getMethod() + " " + response.getHost()
            + response.getRequestLine().getUri() + ": " + response.getStatusLine().toString();
    if (hasBody) {
        message += "\n" + responseBody;
    }
    assertEquals(message, responseException.getMessage());
}

From source file:com.strato.hidrive.api.connection.httpgateway.request.PostRequest.java

@SuppressWarnings("unchecked")
protected HttpRequestBase createHttpRequest(String requestUri, HttpRequestParamsVisitor<?> visitor)
        throws UnsupportedEncodingException {
    HttpPost httpPost = new HttpPost(requestUri);
    //There used StringEntity and some string manipulations instead of UrlEncodedFormEntity due to problem in url encoding ("+" instead "%20")
    //details: http://stackoverflow.com/questions/7915029/how-to-encode-space-as-20-in-urlencodedformentity-while-executing-apache-httppo
    String entityValue = URLEncodedUtils.format((List<NameValuePair>) visitor.getHttpRequestParams(),
            HTTP.UTF_8);/*from  w w  w  .j av  a  2  s . c  o m*/
    entityValue = entityValue.replaceAll("\\+", "%20");
    StringEntity entity = new StringEntity(entityValue, HTTP.UTF_8);
    entity.setContentType(URLEncodedUtils.CONTENT_TYPE);
    httpPost.setEntity(entity);
    //original code:
    //httpPost.setEntity(new UrlEncodedFormEntity((List<? extends NameValuePair>) visitor.getHttpRequestParams(), HTTP.UTF_8));
    return httpPost;
}

From source file:com.braffdev.server.core.http.method.handler.TraceHttpMethodHandler.java

@Override
public HttpResponse handle(PlainRequestEnvironment env, HttpServletRequest request) {
    HttpResponse response = env.getHttpResponse();
    String requestContent = request.toString();
    response.setEntity(new StringEntity(requestContent, ContentType.TEXT_PLAIN));

    return response;
}

From source file:org.surfnet.cruncher.integration.CruncherClientTestIntegration.java

@BeforeClass
public static void beforeClass() throws Exception {
    oauth2AuthServer = new LocalTestServer(null, null);
    oauth2AuthServer.start();/*from  w w w. j  a v  a 2  s .co  m*/
    oauth2AuthServer.register("/oauth2/token", new HttpRequestHandler() {
        @Override
        public void handle(HttpRequest request, HttpResponse response, HttpContext context)
                throws HttpException, IOException {
            response.setEntity(new StringEntity(answer, ContentType.APPLICATION_JSON));
            response.setStatusCode(200);
        }

    });
    String apisOAuth2AuthorizationUrl = String.format("http://%s:%d/oauth2/token",
            oauth2AuthServer.getServiceAddress().getHostName(), oauth2AuthServer.getServiceAddress().getPort());
    cruncherClient = new CruncherClient(cruncherBaseLocation);
    ClientCredentialsClient oauthClient = new ClientCredentialsClient();
    oauthClient.setClientKey("key");
    oauthClient.setClientSecret("secret");
    oauthClient.setOauthAuthorizationUrl(apisOAuth2AuthorizationUrl);
    cruncherClient.setOauthClient(oauthClient);
}

From source file:org.thiesen.hafas.Client.java

public Response doRequest(final Request request) throws ClientException {
    final HttpPost postMethod = new HttpPost(_config.getBaseUrl());

    try {//from w w  w  .ja  v a 2  s.  c o  m
        final String requestString = request.makeStringRepresentation(_config);

        System.out.println(requestString);
        postMethod.setEntity(new StringEntity(requestString, _config.getEncoding().name()));
    } catch (final UnsupportedEncodingException e) {
        throw new Error("Invalid java, UTF-8 not supported", e);
    }

    try {
        final HttpResponse httpResponse = _httpClient.execute(postMethod);

        final StatusLine statusLine = httpResponse.getStatusLine();
        if (statusLine.getStatusCode() != 200) {
            handleErrorResponse(httpResponse, statusLine);
        } else {
            final String extractedResponseContent = extractResponseContent(httpResponse);

            return request.makeResponseFrom(extractedResponseContent);
        }

    } catch (final RuntimeException e) {
        postMethod.abort();
        throw new ClientException(e);
    } catch (final ClientProtocolException e) {
        throw new ClientException(e);
    } catch (final IOException e) {
        throw new ClientException(e);
    }

    throw new RuntimeException("Should never arrive here!");

}

From source file:org.forgerock.openam.mobile.commons.JSONRestRequest.java

/**
 * Inserts the supplied JSON data into the request
 *///from   www. j av  a 2 s  .c  o  m
public void insertData(JSONObject json) {

    if (json == null) {
        json = new JSONObject();
    }

    try {
        HttpPost request = getRequest();
        StringEntity entity = new StringEntity(json.toString(), HTTP.UTF_8);
        entity.setContentType(CONTENT_TYPE);
        request.setEntity(entity);
    } catch (UnsupportedEncodingException e) {
        fail(TAG, "Unable to set entity");
    }
}