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:org.n52.ses.services.wfs.WFSConnector.java

/**
 * Sends a request to a web service. Can deal with SOAP messages and http-authentification.
 * /*from www . j av a2s .c  o m*/
 * @param xmlRequest
 *       the request
 * @return
 *       the response from the web service
 * @throws Exception 
 */
private XmlObject sendHttpPost(XmlObject xmlRequest) throws Exception {
    String request = xmlRequest.xmlText(requestOptions);

    // authentication
    if (userNamePW != null) {
        String username = userNamePW.get(USER_KEY);
        String password = userNamePW.get(PASSWORD_KEY);
        client.setAuthentication(new BasicAuthenticator(username, password));
    }

    SESHttpResponse resp = client.sendPost(new URL(wfsURL), request, ContentType.create("text/xml", "utf-8"));
    if (resp.getContentType().contains("xml")) {
        return XmlObject.Factory.parse(resp.getContent());
    }
    return null;
}

From source file:ee.ria.xroad.common.util.AbstractHttpSender.java

protected static StringEntity createStringEntity(String content, String contentType) {
    return new StringEntity(content, ContentType.create(contentType, MimeUtils.UTF8));
}

From source file:org.apache.camel.component.olingo2.api.impl.Olingo2AppImpl.java

/**
 * Create Olingo2 Application with custom HTTP client builder.
 *
 * @param serviceUri Service Application base URI.
 * @param builder custom HTTP client builder.
 */// w w w  . jav  a 2 s . co  m
public Olingo2AppImpl(String serviceUri, HttpAsyncClientBuilder builder) {
    setServiceUri(serviceUri);

    if (builder == null) {
        this.client = HttpAsyncClients.createDefault();
    } else {
        this.client = builder.build();
    }
    this.client.start();
    this.contentType = ContentType.create("application/json", Consts.UTF_8);
}

From source file:net.sourceforge.jwbf.core.actions.HttpActionClient.java

@VisibleForTesting
void applyToEntityBuilder(String key, Object value, Charset charset, MultipartEntityBuilder entityBuilder) {
    if (value != null) {
        if (value instanceof String) {
            String text = (String) value;
            entityBuilder.addTextBody(key, text, ContentType.create("*/*", charset));
        } else if (value instanceof File) {
            File file = (File) value;
            entityBuilder.addBinaryBody(key, file);
        } else {/*from   w w  w.j  ava 2  s .c o  m*/
            String canonicalName = value.getClass().getCanonicalName();
            throw new UnsupportedOperationException("No Handler found for " + canonicalName
                    + ". Only String or File is accepted, " + "because http parameters knows no other types.");
        }
    }
}

From source file:com.flipkart.bifrost.http.HttpCallCommand.java

private HttpUriRequest generateRequestObject() throws BifrostException {
    try {//from  w w w  .  j a  va  2 s  .c o m
        switch (requestType) {
        case HTTP_GET:
            return new HttpGet(url);
        case HTTP_POST:
            HttpPost post = new HttpPost(url);
            post.setEntity(new ByteArrayEntity(mapper.writeValueAsBytes(request),
                    ContentType.create(contentType, CharsetUtils.lookup("utf-8"))));
            return post;
        case HTTP_PUT:
            HttpPut put = new HttpPut(url);
            put.setEntity(new ByteArrayEntity(mapper.writeValueAsBytes(request),
                    ContentType.create(contentType, CharsetUtils.lookup("utf-8"))));
            return put;
        case HTTP_DELETE:
            return new HttpDelete(url);
        }
    } catch (JsonProcessingException e) {
        throw new BifrostException(BifrostException.ErrorCode.SERIALIZATION_ERROR,
                "Could not serialize request body");
    }
    throw new BifrostException(BifrostException.ErrorCode.UNSUPPORTED_REQUEST_TYPE,
            String.format("Request type %s is not supported", requestType.name()));
}

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

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

From source file:de.hska.ld.oidc.client.SSSClient.java

public SSSLivingdocsResponseDto createDocument(Document document, String discussionId, String accessToken)
        throws IOException, AuthenticationNotValidException {
    String url = null;//from w  w w.j a va2 s .c  o m
    if (getSssAPIVersion() == 1) {
        url = env.getProperty("sss.server.endpoint") + "/livingdocs/livingdocs/";
    } else {
        url = env.getProperty("sss.server.endpoint") + "/rest/livingdocs/";
    }

    HttpClient client = getHttpClientFor(url);
    HttpPost post = new HttpPost(url);
    addHeaderInformation(post, accessToken);

    SSSLivingdocsRequestDto sssLivingdocsRequestDto = new SSSLivingdocsRequestDto();
    String externalServerAddress = env.getProperty("sss.document.name.prefix");
    sssLivingdocsRequestDto.setUri(externalServerAddress + document.getId());
    sssLivingdocsRequestDto.setDescription(document.getDescription());
    if (discussionId != null) {
        sssLivingdocsRequestDto.setDiscussion(discussionId);
    }
    sssLivingdocsRequestDto.setLabel(document.getTitle());
    String sssLivingdocsRequestDtoString = mapper.writeValueAsString(sssLivingdocsRequestDto);
    StringEntity stringEntity = new StringEntity(sssLivingdocsRequestDtoString,
            ContentType.create("application/json", "UTF-8"));
    post.setEntity(stringEntity);

    HttpResponse response = client.execute(post);
    System.out.println("Response Code : " + response.getStatusLine().getStatusCode());

    if (response.getStatusLine().getStatusCode() != 200) {
        throw new AuthenticationNotValidException();
    }

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

        StringBuilder result = new StringBuilder();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        if (result.toString().contains("\"error_description\":\"Invalid access token:")) {
            throw new ValidationException("access token is invalid");
        }
        return mapper.readValue(result.toString(), SSSLivingdocsResponseDto.class);
    } catch (Exception e) {
        return null;
    } finally {
        if (rd != null) {
            rd.close();
        }
    }
}

From source file:com.intuit.tank.httpclient4.TankHttpClient4.java

@Override
public void doPost(BaseRequest request) {
    HttpPost httppost = new HttpPost(request.getRequestUrl());
    String requestBody = request.getBody();
    HttpEntity entity = null;/*from w  w  w.  j a  v  a  2  s  .c o m*/
    if (BaseRequest.CONTENT_TYPE_MULTIPART.equalsIgnoreCase(request.getContentType())) {
        entity = buildParts(request);
    } else {
        entity = new StringEntity(requestBody,
                ContentType.create(request.getContentType(), request.getContentTypeCharSet()));
    }
    httppost.setEntity(entity);
    sendRequest(request, httppost, requestBody);
}

From source file:nl.nn.adapterframework.http.mime.MultipartEntityBuilder.java

private MultipartEntity buildEntity() {
    String boundaryCopy = boundary;
    if (boundaryCopy == null && contentType != null) {
        boundaryCopy = contentType.getParameter("boundary");
    }// w  w  w. j  av  a  2s . co m
    if (boundaryCopy == null) {
        boundaryCopy = generateBoundary();
    }
    Charset charsetCopy = charset;
    if (charsetCopy == null && contentType != null) {
        charsetCopy = contentType.getCharset();
    }

    List<NameValuePair> paramsList = new ArrayList<NameValuePair>(5);
    paramsList.add(new BasicNameValuePair("boundary", boundaryCopy));
    if (charsetCopy != null) {
        paramsList.add(new BasicNameValuePair("charset", charsetCopy.name()));
    }

    String subtypeCopy = DEFAULT_SUBTYPE;
    if (mtom) {
        paramsList.add(new BasicNameValuePair("type", "application/xop+xml"));
        paramsList.add(new BasicNameValuePair("start", firstPart));
        paramsList.add(new BasicNameValuePair("start-info", "text/xml"));
        subtypeCopy = MTOM_SUBTYPE;
    }

    NameValuePair[] params = paramsList.toArray(new NameValuePair[paramsList.size()]);
    ContentType contentTypeCopy = contentType != null ? contentType.withParameters(params)
            : ContentType.create("multipart/" + subtypeCopy, params);

    List<FormBodyPart> bodyPartsCopy = bodyParts != null ? new ArrayList<FormBodyPart>(bodyParts)
            : Collections.<FormBodyPart>emptyList();
    MultipartForm form = new MultipartForm(charsetCopy, boundaryCopy, bodyPartsCopy);
    return new MultipartEntity(form, contentTypeCopy, form.getTotalLength());
}