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

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

Introduction

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

Prototype

public Header getContentType() 

Source Link

Usage

From source file:org.imsglobal.caliper.request.ApacheHttpRequestor.java

/**
 * Post envelope./*from   www . j  ava 2 s .c  o m*/
 * @param data
 * @return status
 */
@Override
public boolean send(Sensor sensor, List<T> data) throws IOException {
    boolean status = Boolean.FALSE;

    if (log.isDebugEnabled()) {
        log.debug("Entering send()...");
    }

    // Check if HttpClient is initialized.
    checkInitialized();

    // Create mapper
    ObjectMapper mapper = JsonObjectMapper.create(options.getJsonInclude());

    // Create envelope, serialize it as a JSON string.
    Envelope<T> envelope = createEnvelope(sensor, DateTime.now(), data);

    // Serialize envelope with mapper
    String json = serializeEnvelope(envelope, mapper);

    // Create an HTTP StringEntity payload with the envelope JSON.
    StringEntity payload = generatePayload(json, ContentType.APPLICATION_JSON);

    // Do the post
    HttpPost httpPost = new HttpPost(this.getOptions().getHost());
    httpPost.setHeader("Authorization", this.getOptions().getApiKey());
    httpPost.setHeader(payload.getContentType());

    httpPost.setEntity(payload);
    response = httpClient.execute(httpPost);

    if (response.getStatusLine().getStatusCode() != 200 && response.getStatusLine().getStatusCode() != 201) {
        int statusCode = response.getStatusLine().getStatusCode();
        response.close();
        throw new RuntimeException("Failed : HTTP error code : " + statusCode);
    } else {
        if (log.isDebugEnabled()) {
            log.debug(response.getStatusLine().toString());
            log.debug(EntityUtils.toString(response.getEntity()));
        }

        response.close();
        status = Boolean.TRUE;

        if (log.isDebugEnabled()) {
            log.debug("Exiting send()...");
        }
    }

    return status;
}

From source file:ste.web.http.beanshell.BugFreeBeanShellUtils.java

@Test
public void formUrlEncodedParameters() throws Exception {
    BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("get", TEST_URI09);
    StringEntity e = new StringEntity(TEST_QUERY_STRING);
    e.setContentType(ContentType.APPLICATION_FORM_URLENCODED.getMimeType());
    request.setEntity(e);/*from  ww  w .  ja  v a  2s  . c o m*/

    HttpSessionContext context = new HttpSessionContext();
    context.setAttribute(HttpCoreContext.HTTP_CONNECTION, getConnection());
    request.addHeader(HTTP.CONTENT_TYPE, e.getContentType().getValue());

    Interpreter i = new Interpreter();
    BeanShellUtils.setup(i, request, RESPONSE_OK, context);

    then(i.get(TEST_URL_PARAM1)).isEqualTo(TEST_VALUE1);
    then(i.get(TEST_URL_PARAM2)).isEqualTo(TEST_VALUE2);

    e.setContentType(ContentType.APPLICATION_FORM_URLENCODED.getMimeType() + " ; charset=UTF-8");
    request.setHeader(HTTP.CONTENT_TYPE, e.getContentType().getValue());

    i = new Interpreter();
    BeanShellUtils.setup(i, request, RESPONSE_OK, context);

    then(i.get(TEST_URL_PARAM1)).isEqualTo(TEST_VALUE1);
    then(i.get(TEST_URL_PARAM2)).isEqualTo(TEST_VALUE2);

}

From source file:org.phenotips.remote.client.script.RemoteMatchingScriptService.java

public JSONObject sendRequest(String patientId, String remoteServerId, boolean async, boolean periodic,
        int addTopNGenes) {
    this.logger.error("Sending outgoing request for patient [{}] to server [{}]", patientId, remoteServerId);
    if (async) {/*from  w  ww. j  a  v a 2 s . c  o m*/
        this.logger.error("Requesting async replies");
    }
    if (periodic) {
        this.logger.error("Requesting periodic replies");
    }

    XWikiContext context = this.getContext();

    BaseObject configurationObject = XWikiAdapter.getRemoteConfigurationGivenRemoteName(remoteServerId,
            context);

    if (configurationObject == null) {
        logger.error("Requested matching server is not configured: [{}]", remoteServerId);
        return generateScriptErrorReply(ApiConfiguration.ERROR_NOT_SENT,
                "requested matching server [" + remoteServerId + "] is not configured");
    }

    // TODO: get API version from server configuration

    String apiVersion = "v1";
    ApiDataConverter apiVersionSpecificConverter = this.apiFactory.getApiVersion(apiVersion);

    DefaultOutgoingSearchRequest request = new DefaultOutgoingSearchRequest(patientId, remoteServerId);
    if (periodic) {
        request.setQueryType(ApiConfiguration.REQUEST_QUERY_TYPE_PERIODIC);
    }
    if (async) {
        request.setResponseType(ApiConfiguration.REQUEST_RESPONSE_TYPE_ASYNCHRONOUS);
    }

    JSONObject requestJSON;
    try {
        requestJSON = apiVersionSpecificConverter.getOutgoingRequestToJSONConverter().toJSON(request,
                addTopNGenes);
    } catch (ApiViolationException ex) {
        return generateScriptErrorReply(ApiConfiguration.ERROR_NOT_SENT, ex.getMessage());
    }
    if (requestJSON == null) {
        this.logger.error("Unable to convert patient to JSON: [{}]", patientId);
        return generateScriptErrorReply(ApiConfiguration.ERROR_NOT_SENT,
                "unable to convert patient with ID [" + patientId.toString() + "] to JSON");
    }

    CloseableHttpClient client = HttpClients.createDefault();

    StringEntity jsonEntity = new StringEntity(requestJSON.toString(),
            ContentType.create("application/json", "utf-8"));

    // TODO: hack to make charset lower-cased so that GeneMatcher accepts it
    jsonEntity.setContentType("application/json; charset=utf-8");
    this.logger.error("Using content type: [{}]", jsonEntity.getContentType().toString());

    String key = configurationObject.getStringValue(ApplicationConfiguration.CONFIGDOC_REMOTE_KEY_FIELD);
    String baseURL = configurationObject
            .getStringValue(ApplicationConfiguration.CONFIGDOC_REMOTE_BASE_URL_FIELD);
    if (baseURL.charAt(baseURL.length() - 1) != '/') {
        baseURL += "/";
    }
    String targetURL = baseURL + ApiConfiguration.REMOTE_URL_SEARCH_ENDPOINT;

    this.logger.error("Sending matching request to [" + targetURL + "]: " + requestJSON.toString());

    CloseableHttpResponse httpResponse;
    try {
        HttpPost httpRequest = new HttpPost(targetURL);
        httpRequest.setEntity(jsonEntity);
        httpRequest.setHeader(ApiConfiguration.HTTPHEADER_KEY_PARAMETER, key);
        httpResponse = client.execute(httpRequest);
    } catch (javax.net.ssl.SSLHandshakeException ex) {
        this.logger.error(
                "Error sending matching request to [" + targetURL + "]: SSL handshake exception: [{}]", ex);
        return generateScriptErrorReply(ApiConfiguration.ERROR_NOT_SENT, "SSL handshake problem");
    } catch (Exception ex) {
        this.logger.error("Error sending matching request to [" + targetURL + "]: [{}]", ex);
        return generateScriptErrorReply(ApiConfiguration.ERROR_NOT_SENT, ex.getMessage());
    }

    try {
        Integer httpStatus = (Integer) httpResponse.getStatusLine().getStatusCode();
        String stringReply = EntityUtils.toString(httpResponse.getEntity());

        logger.error("Reply to matching request: STATUS: [{}], DATA: [{}]", httpStatus, stringReply);

        JSONObject replyJSON = getParsedJSON(stringReply);

        if (StringUtils.equalsIgnoreCase(request.getQueryType(), ApiConfiguration.REQUEST_QUERY_TYPE_PERIODIC)
                || StringUtils.equalsIgnoreCase(request.getResponseType(),
                        ApiConfiguration.REQUEST_RESPONSE_TYPE_ASYNCHRONOUS)) {
            // get query ID assigned by the remote server and saveto DB
            if (!replyJSON.has(ApiConfiguration.JSON_RESPONSE_ID)) {
                this.logger.error("Can not store outgoing request: no queryID is provided by remote server");
            } else {
                String queruID = replyJSON.getString(ApiConfiguration.JSON_RESPONSE_ID);
                this.logger.error("Remote server assigned id to the submitted query: [{}]", queruID);
                request.setQueryID(replyJSON.getString(ApiConfiguration.JSON_RESPONSE_ID));
                requestStorageManager.saveOutgoingRequest(request);
            }
        }

        return generateScriptReply(httpStatus, replyJSON);
    } catch (Exception ex) {
        this.logger.error("Error processing matching request reply to [" + targetURL + "]: [{}]", ex);
        return generateScriptReply(ApiConfiguration.ERROR_INTERNAL, null);
    }
}

From source file:org.ellis.yun.search.test.httpclient.HttpClientTest.java

@Test
@SuppressWarnings("deprecation")
public void testStringEntity() throws Exception {
    StringEntity myEntity = new StringEntity("important message", "UTF-8");
    System.out.println(myEntity.getContentType() + "");
    System.out.println(myEntity.getContentLength() + "");
    System.out.println(EntityUtils.getContentCharSet(myEntity));
    System.out.println(EntityUtils.toString(myEntity));
    System.out.println(EntityUtils.toByteArray(myEntity).length + "");
}

From source file:com.android.callstat.common.net.ConnectionThread.java

/**
 * A helper method to send or retrieve data through HTTP protocol.
 * /*from   w  ww  . j a  va 2 s  . c o  m*/
 * @param token
 *            The token to identify the sending progress.
 * @param url
 *            The URL used in a GET request. Null when the method is
 *            HTTP_POST_METHOD.
 * @param pdu
 *            The data to be POST. Null when the method is HTTP_GET_METHOD.
 * @param method
 *            HTTP_POST_METHOD or HTTP_GET_METHOD.
 * @return A byte array which contains the response data. If an HTTP error
 *         code is returned, an IOException will be thrown.
 * @throws IOException
 *             if any error occurred on network interface or an HTTP error
 *             code(&gt;=400) returned from the server.
 */
private byte[] httpConnection(Context context, boolean isProxySet, MyHttpClient client, String proxyHost,
        int proxyPort, Request request) throws IOException {
    if (request.getUri() == null) {
        throw new IllegalArgumentException("URL must not be null.");
    }
    int timeout = (int) request.getmTimeout();
    if (timeout != 0 && timeout < 5000) {
        timeout = 5000;
    }
    client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);
    client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout);
    try {
        URI hostUrl = new URI(request.getUri());
        HttpHost target = new HttpHost(hostUrl.getHost(), hostUrl.getPort(), HttpHost.DEFAULT_SCHEME_NAME);
        HttpLog.d("URL:" + request.getUri() + " Host:" + hostUrl.getHost() + " Port:" + hostUrl.getPort());

        HttpRequest req = null;
        switch (request.getMethod()) {
        case HTTP_POST_METHOD:
            HttpPost post = new HttpPost(request.getUri());
            HttpEntity content = request.getHttpEntity();
            if (content != null) {
                post.setEntity(content);
                if (content instanceof StringEntity) {
                    final StringEntity stringEntity = (StringEntity) content;
                    post.setHeader(stringEntity.getContentEncoding());
                    post.setHeader(stringEntity.getContentType());
                }
            }
            req = post;
            break;
        case HTTP_GET_METHOD:
            req = new HttpGet(request.getUri());
            break;
        default:
            HttpLog.e("Unknown HTTP method: " + request.getMethod() + ". Must be one of POST["
                    + HTTP_POST_METHOD + "] or GET[" + HTTP_GET_METHOD + "].");
            return null;
        }
        HttpResponse response = null;
        if (CallStatUtils.isOMS()) {
            setRequest(response, isProxySet, req, client, proxyHost, proxyPort, request);
            response = client.execute(target, req);
        } else {
            if (CallStatUtils.isMOBILE(mContext)) {
                String apn = CallStatUtils.getAPN(mContext);
                if (!StringUtil.isNullOrWhitespaces(apn)) {
                    if (apn.equals("CMWAP")) {
                        HttpClient httpclient = new DefaultHttpClient();
                        HttpHost proxy = new HttpHost("10.0.0.172", 80, "http");
                        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
                        response = httpclient.execute(target, req);
                    } else {
                        setRequest(response, isProxySet, req, client, proxyHost, proxyPort, request);
                        response = client.execute(target, req);
                    }
                } else {
                    setRequest(response, isProxySet, req, client, proxyHost, proxyPort, request);
                    response = client.execute(target, req);
                }
            } else {
                setRequest(response, isProxySet, req, client, proxyHost, proxyPort, request);
                response = client.execute(target, req);
            }

        }
        StatusLine status = response.getStatusLine();
        request.getEventHandler().status(status.getProtocolVersion().getMajor(),
                status.getProtocolVersion().getMinor(), status.getStatusCode(), status.getReasonPhrase());
        switch (status.getStatusCode()) {
        case 200:
            break;
        case 304:
            request.getEventHandler().endData(null, 0);
            return null;
        default:
            request.getEventHandler().endData(null, 0);
            throw new IOException(
                    "HTTP error: " + status.getReasonPhrase() + " CODE:" + status.getStatusCode());
        }
        Headers headers = new Headers();
        readResponseHeaders(headers, response);
        request.getEventHandler().headers(headers);

        HttpEntity entity = response.getEntity();
        byte[] body = null;
        if (entity != null) {
            try {
                int contentLength = (int) entity.getContentLength();
                if (contentLength > 0) {
                    body = new byte[contentLength];
                    // DataInputStream dis = new
                    // DataInputStream(entity.getContent());
                    InputStream in = entity.getContent();
                    int offset = 0;
                    int length = contentLength;
                    try {
                        while (length > 0) {
                            int result = in.read(body, offset, length);
                            HttpLog.v("################result:" + result);
                            offset += result;
                            length -= result;
                            if (length <= 0) {
                                request.getEventHandler().endData(body, contentLength);
                            }
                        }
                    } finally {
                        try {
                            in.close();
                            // request.mLoadListener.loaded(body,
                            // contentLength);
                            // if(length == 0)
                            // CallbackProxy.getHandler().onFinishResourceLoading(body,
                            // contentLength, request.mLoadListener);
                        } catch (IOException e) {
                            HttpLog.e("Error closing input stream: " + e.getMessage());
                        }
                    }
                } else {
                    ByteArrayBuilder dataBuilder = new ByteArrayBuilder();
                    body = new byte[8192];
                    InputStream in = entity.getContent();
                    int result = 0;
                    int count = 0;
                    int lowWater = body.length / 2;
                    try {
                        while (result != -1) {
                            result = in.read(body, count, body.length - count);
                            if (result != -1) {
                                HttpLog.v("################result:" + result);
                                count += result;
                            }
                            if (result == -1 || count >= lowWater) {
                                dataBuilder.append(body, 0, count);
                                count = 0;
                            }
                            if (result == -1) {
                                if (dataBuilder.getByteSize() > 0) {
                                    byte[] cert = new byte[dataBuilder.getByteSize()];
                                    int offset = 0;
                                    while (true) {
                                        ByteArrayBuilder.Chunk c = dataBuilder.getFirstChunk();
                                        if (c == null)
                                            break;
                                        if (c.mLength != 0) {
                                            System.arraycopy(c.mArray, 0, cert, offset, c.mLength);
                                            offset += c.mLength;
                                        }
                                        c.release();
                                    }
                                    request.getEventHandler().endData(cert, cert.length);
                                }
                            }
                        }
                    } finally {
                        try {
                            in.close();
                        } catch (IOException e) {
                            HttpLog.e("Error closing input stream: " + e.getMessage());
                        }
                    }

                }
            } finally {
                if (entity != null) {
                    entity.consumeContent();
                }
            }
        }
        return body;
    } catch (URISyntaxException e) {
        // TODO Auto-generated catch block
        request.getEventHandler().error(EventHandler.ERROR_BAD_URL, e.getMessage());
        e.printStackTrace();
    } catch (IllegalStateException e) {
        request.getEventHandler().error(EventHandler.ERROR, e.getMessage());
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        request.getEventHandler().error(EventHandler.ERROR_BAD_URL, e.getMessage());
        e.printStackTrace();
    } catch (SocketException e) {
        request.getEventHandler().error(EventHandler.ERROR, e.getMessage());
        e.printStackTrace();
    } catch (ConnectTimeoutException e) {
        request.getEventHandler().error(EventHandler.ERROR_TIMEOUT, e.getMessage());
        e.printStackTrace();
    } catch (Exception e) {
        request.getEventHandler().error(EventHandler.ERROR, e.getMessage());
        e.printStackTrace();
    }
    return null;
}

From source file:org.ebayopensource.twin.TwinConnection.java

@SuppressWarnings("unchecked")
private Map<String, Object> _request(String method, String path, Map<String, Object> body,
        JSONRecognizer... recognizers) throws IOException, TwinException {
    String uri = url + path;/*from   w w  w .  ja v a 2 s .  c o  m*/
    HttpRequest request;
    if (body == null) {
        BasicHttpRequest r = new BasicHttpRequest(method, uri);
        request = r;
    } else {
        BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest(method, uri);
        StringEntity entity;
        try {
            entity = new StringEntity(JSON.encode(body), "utf-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        entity.setContentType("application/json; charset=utf-8");
        r.setEntity(entity);
        request = r;
    }

    HttpClient client = getClient();
    try {
        HttpResponse response = client.execute(new HttpHost(url.getHost(), url.getPort()), request);
        HttpEntity entity = response.getEntity();
        if (entity == null)
            return null;
        String contentType = entity.getContentType().getValue();
        boolean isJson = (contentType != null)
                && ("application/json".equals(contentType) || contentType.startsWith("application/json;"));
        String result = null;

        InputStream in = entity.getContent();
        try {
            Reader r = new InputStreamReader(in, "UTF-8");
            StringBuilder sb = new StringBuilder();
            char[] buf = new char[256];
            int read;
            while ((read = r.read(buf, 0, buf.length)) >= 0)
                sb.append(buf, 0, read);
            r.close();

            result = sb.toString();
        } finally {
            try {
                in.close();
            } catch (Exception e) {
            }
        }

        int code = response.getStatusLine().getStatusCode();
        if (code >= 400) {
            if (isJson) {
                try {
                    throw deserializeException((Map<String, Object>) JSON.decode(result));
                } catch (IllegalArgumentException e) {
                    throw TwinError.UnknownError.create("Couldn't parse error response: \n" + result, e);
                }
            }
            if (code == 404)
                throw TwinError.UnknownCommand.create("Got server response " + code + " for request " + uri);
            else
                throw TwinError.UnknownError
                        .create("Got server response " + code + " for request " + uri + "\nBody is " + result);
        }

        if (!isJson)
            throw TwinError.UnknownError.create(
                    "Got wrong content type " + contentType + " for request " + uri + "\nBody is " + result);

        try {
            return (Map<String, Object>) JSON.decode(result, recognizers);
        } catch (Exception e) {
            throw TwinError.UnknownError
                    .create("Malformed JSON result for request " + uri + ": \nBody is " + result, e);
        }
    } catch (ClientProtocolException e) {
        throw new IOException(e);
    }
}

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

public void testParseEntity() throws IOException {
    {/*from  w w  w  .j  av a  2 s  .com*/
        IllegalStateException ise = expectThrows(IllegalStateException.class,
                () -> restHighLevelClient.parseEntity(null, null));
        assertEquals("Response body expected but not returned", ise.getMessage());
    }
    {
        IllegalStateException ise = expectThrows(IllegalStateException.class,
                () -> restHighLevelClient.parseEntity(new StringEntity("", (ContentType) null), null));
        assertEquals("Elasticsearch didn't return the [Content-Type] header, unable to parse response body",
                ise.getMessage());
    }
    {
        StringEntity entity = new StringEntity("", ContentType.APPLICATION_SVG_XML);
        IllegalStateException ise = expectThrows(IllegalStateException.class,
                () -> restHighLevelClient.parseEntity(entity, null));
        assertEquals("Unsupported Content-Type: " + entity.getContentType().getValue(), ise.getMessage());
    }
    {
        CheckedFunction<XContentParser, String, IOException> entityParser = parser -> {
            assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
            assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken());
            assertTrue(parser.nextToken().isValue());
            String value = parser.text();
            assertEquals(XContentParser.Token.END_OBJECT, parser.nextToken());
            return value;
        };
        HttpEntity jsonEntity = new StringEntity("{\"field\":\"value\"}", ContentType.APPLICATION_JSON);
        assertEquals("value", restHighLevelClient.parseEntity(jsonEntity, entityParser));
        HttpEntity yamlEntity = new StringEntity("---\nfield: value\n", ContentType.create("application/yaml"));
        assertEquals("value", restHighLevelClient.parseEntity(yamlEntity, entityParser));
        HttpEntity smileEntity = createBinaryEntity(SmileXContent.contentBuilder(),
                ContentType.create("application/smile"));
        assertEquals("value", restHighLevelClient.parseEntity(smileEntity, entityParser));
        HttpEntity cborEntity = createBinaryEntity(CborXContent.contentBuilder(),
                ContentType.create("application/cbor"));
        assertEquals("value", restHighLevelClient.parseEntity(cborEntity, entityParser));
    }
}

From source file:org.klnusbaum.udj.network.ServerConnection.java

public static HttpResponse doPut(URI uri, String ticketHash, String payload, Set<Header> headers)
        throws IOException {
    Log.d(TAG, "Doing put to uri: " + uri);
    Log.d(TAG, "Put payload is: " + (payload != null ? payload : "no payload"));
    final HttpPut put = new HttpPut(uri);
    put.addHeader(TICKET_HASH_HEADER, ticketHash);
    for (Header h : headers) {
        put.addHeader(h);//from   ww w  .  j  av a2s.co  m
    }
    if (payload != null) {
        StringEntity entity = new StringEntity(payload);
        entity.setContentType("text/json");
        put.addHeader(entity.getContentType());
        put.setEntity(entity);
    }
    return getHttpClient().execute(put);
}