Example usage for org.apache.http.entity ContentType create

List of usage examples for org.apache.http.entity ContentType create

Introduction

In this page you can find the example usage for org.apache.http.entity ContentType create.

Prototype

public static ContentType create(String str, String str2) throws UnsupportedCharsetException 

Source Link

Usage

From source file:com.github.tomakehurst.wiremock.testsupport.WireMockTestClient.java

public WireMockResponse postWithBody(String url, String body, String bodyMimeType, String bodyEncoding) {
    return post(url, new StringEntity(body, ContentType.create(bodyMimeType, bodyEncoding)));
}

From source file:org.phenotips.data.internal.MonarchPatientScorer.java

@Override
public double getScore(Patient patient) {
    String key = getCacheKey(patient);
    PatientSpecificity specificity = this.cache.get(key);
    if (specificity != null) {
        return specificity.getScore();
    }//  w w  w  .  j a  v  a 2  s  .c  o  m
    if (patient.getFeatures().isEmpty()) {
        this.cache.set(key, new PatientSpecificity(0, now(), SCORER_NAME));
        return 0;
    }
    CloseableHttpResponse response = null;
    try {
        JSONObject data = new JSONObject();
        JSONArray features = new JSONArray();
        for (Feature f : patient.getFeatures()) {
            if (StringUtils.isNotEmpty(f.getId())) {
                JSONObject featureObj = new JSONObject(Collections.singletonMap("id", f.getId()));
                if (!f.isPresent()) {
                    featureObj.put("isPresent", false);
                }
                features.put(featureObj);
            }
        }
        data.put("features", features);

        HttpPost method = new HttpPost(this.scorerURL);
        method.setEntity(new StringEntity("annotation_profile=" + URLEncoder.encode(data.toString(), "UTF-8"),
                ContentType.create("application/x-www-form-urlencoded", Consts.UTF_8)));

        RequestConfig config = RequestConfig.custom().setSocketTimeout(2000).build();
        method.setConfig(config);
        response = this.client.execute(method);
        JSONObject score = new JSONObject(
                IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8));
        specificity = new PatientSpecificity(score.getDouble("scaled_score"), now(), SCORER_NAME);
        this.cache.set(key, specificity);
        return specificity.getScore();
    } catch (Exception ex) {
        // Just return failure below
        this.logger.error(
                "Failed to compute specificity score for patient [{}] using the monarch server [{}]: {}",
                patient.getDocumentReference(), this.scorerURL, ex.getMessage());
    } finally {
        if (response != null) {
            try {
                EntityUtils.consumeQuietly(response.getEntity());
                response.close();
            } catch (IOException ex) {
                // Not dangerous
            }
        }
    }
    return -1;
}

From source file:io.coala.capability.online.FluentHCOnlineCapability.java

public static HttpEntity toFormEntity(final List<NameValuePair> paramList) {
    final ContentType contentType = ContentType.create(URLEncodedUtils.CONTENT_TYPE, Consts.ISO_8859_1);
    final Charset charset = contentType != null ? contentType.getCharset() : null;
    final String s = URLEncodedUtils.format(paramList, charset != null ? charset.name() : null);
    byte[] raw;/*from   w  w w  . j ava  2 s . c o  m*/
    try {
        raw = charset != null ? s.getBytes(charset.name()) : s.getBytes();
    } catch (UnsupportedEncodingException ex) {
        raw = s.getBytes();
    }
    return new ApacheInternalByteArrayEntity(raw, contentType);
}

From source file:com.microsoft.services.odata.unittests.WireMockTestClient.java

public WireMockResponse patchWithBody(String url, String body, String bodyMimeType, String bodyEncoding)
        throws UnsupportedEncodingException {
    return patch(url, new StringEntity(body, ContentType.create(bodyMimeType, bodyEncoding).toString()));
}

From source file:org.n52.oxf.sos.adapter.wrapper.SOSWrapper.java

private void processOptionalMimetypeParameter(final MimetypeAwareRequestParameters parameters,
        final ParameterContainer parameterContainer) throws OXFException {
    if (parameters.isSetMimetype() && parameters.isValid()) {
        final String type = parameters.getSingleValue(MimetypeAwareRequestParameters.MIME_TYPE);
        final String charSet = parameters.getSingleValue(MimetypeAwareRequestParameters.CHARSET);
        final ContentType contentType = ContentType.create(type, Charset.forName(charSet));
        parameterContainer.addParameterShell(MIMETYPE, contentType.getMimeType());
        parameterContainer.addParameterShell(ENCODING, charSet);
    }//from  ww w.j av a  2  s  .  c o  m
}

From source file:net.ymate.platform.module.wechat.support.HttpClientHelper.java

public String doPost(String url, String content) throws Exception {
    CloseableHttpClient _httpClient = __doBuildHttpClient();
    try {// w  ww .j a va  2s . c o m
        _LOG.debug("Request URL [" + url + "] PostBody [" + content + "]");
        String _result = _httpClient.execute(
                RequestBuilder.post().setUri(url)
                        .setEntity(EntityBuilder.create().setContentEncoding(DEFAULT_CHARSET)
                                .setContentType(ContentType.create("application/x-www-form-urlencoded",
                                        DEFAULT_CHARSET))
                                .setText(content).build())
                        .build(),
                new ResponseHandler<String>() {

                    public String handleResponse(HttpResponse response) throws IOException {
                        return EntityUtils.toString(response.getEntity(), DEFAULT_CHARSET);
                    }

                });
        _LOG.debug("Request URL [" + url + "] Response [" + _result + "]");
        return _result;
    } finally {
        _httpClient.close();
    }
}

From source file:org.wso2.msf4j.client.ApacheHttpClient.java

private ContentType getContentType(Request request) {
    ContentType contentType = ContentType.DEFAULT_TEXT;
    for (Map.Entry<String, Collection<String>> entry : request.headers().entrySet()) {
        if (entry.getKey().equalsIgnoreCase("Content-Type")) {
            Collection values = entry.getValue();
            if (values != null && !values.isEmpty()) {
                contentType = ContentType.create(entry.getValue().iterator().next(), request.charset());
                break;
            }//from   ww w.  j  a v a2  s  .co m
        }
    }
    return contentType;
}

From source file:lucee.commons.net.http.HTTPEngine.java

public static ContentType toContentType(String mimetype, String charset) {
    ContentType ct = null;//from  www  . jav a2  s  .  c om
    if (!StringUtil.isEmpty(mimetype, true)) {
        if (!StringUtil.isEmpty(charset, true))
            ct = ContentType.create(mimetype.trim(), charset.trim());
        else
            ct = ContentType.create(mimetype.trim());
    }
    return ct;
}

From source file:com.streamreduce.util.HTTPUtils.java

/**
 * Opens a connection to the specified URL with the supplied username and password,
 * if supplied, and then reads the contents of the URL.
 *
 * @param url             the url to open and read from
 * @param method          the method to use for the request
 * @param data            the request body as string
 * @param mediaType       the media type of the request
 * @param username        the username, if any
 * @param password        the password, if any
 * @param requestHeaders  the special request headers to send
 * @param responseHeaders save response headers
 * @return the read string from the// w w  w  . j  a  v  a 2  s.c om
 * @throws InvalidCredentialsException if the connection credentials are invalid
 * @throws IOException                 if there is a problem with the request
 */
public static String openUrl(String url, String method, String data, String mediaType,
        @Nullable String username, @Nullable String password, @Nullable List<Header> requestHeaders,
        @Nullable List<Header> responseHeaders) throws InvalidCredentialsException, IOException {

    String response = null;

    /* Set the cookie policy */
    httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

    /* Set the user agent */
    httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, Constants.NODEABLE_HTTP_USER_AGENT);

    HttpContext context = new BasicHttpContext();
    HttpRequestBase httpMethod;

    if (method.equals("DELETE")) {
        httpMethod = new HttpDelete(url);
    } else if (method.equals("GET")) {
        httpMethod = new HttpGet(url);
    } else if (method.equals("POST")) {
        httpMethod = new HttpPost(url);
    } else if (method.equals("PUT")) {
        httpMethod = new HttpPut(url);
    } else {
        throw new IllegalArgumentException("The method you specified is not supported.");
    }

    // Put data into the request for POST and PUT requests
    if (method.equals("POST") || method.equals("PUT") && data != null) {
        HttpEntityEnclosingRequestBase eeMethod = (HttpEntityEnclosingRequestBase) httpMethod;

        eeMethod.setEntity(new StringEntity(data, ContentType.create(mediaType, "UTF-8")));
    }

    /* Set the username/password if any */
    if (username != null) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(username, password));
        context.setAttribute(ClientContext.CREDS_PROVIDER, credentialsProvider);
    }

    /* Add request headers if need be */
    if (requestHeaders != null) {
        for (Header header : requestHeaders) {
            httpMethod.addHeader(header);
        }
    }

    LOGGER.debug("Making HTTP request as " + (username != null ? username : "anonymous") + ": " + method + " - "
            + url);

    /* Make the request and read the response */
    try {
        HttpResponse httpResponse = httpClient.execute(httpMethod);
        HttpEntity entity = httpResponse.getEntity();
        if (entity != null) {
            response = EntityUtils.toString(entity);
        }
        int responseCode = httpResponse.getStatusLine().getStatusCode();
        if (responseCode == 401 || responseCode == 403) {
            throw new InvalidCredentialsException("The connection credentials are invalid.");
        } else if (responseCode < 200 || responseCode > 299) {
            throw new IOException(
                    "Unexpected status code of " + responseCode + " for a " + method + " request to " + url);
        }

        if (responseHeaders != null) {
            responseHeaders.addAll(Arrays.asList(httpResponse.getAllHeaders()));
        }
    } catch (IOException e) {
        httpMethod.abort();
        throw e;
    }

    return response;
}