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

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

Introduction

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

Prototype

public void setContentType(Header header) 

Source Link

Usage

From source file:com.wudaosoft.net.httpclient.Request.java

/**
 * //  w  ww  .  ja  v  a2s  .  c  o  m
 * @param workerBuilder
 * @param responseHandler
 * @return
 * @throws Exception
 */
public <T> T doRequest(WorkerBuilder workerBuilder, ResponseHandler<T> responseHandler) throws Exception {

    String method = workerBuilder.getMethod();
    String url = workerBuilder.getUrl();

    Args.notNull(workerBuilder, "WorkerBuilder");
    Args.notEmpty(method, "WorkerBuilder.getMethod()");
    Args.notEmpty(url, "WorkerBuilder.getUrl()");
    Args.notNull(responseHandler, "responseHandler");

    //      if(!workerBuilder.isAnyHost()) {
    if (!isFullUrl(url)) {
        //         notFullUrl(url);
        Args.notEmpty(hostConfig.getHostUrl(), "HostConfig.getHostUrl()");
        url = hostConfig.getHostUrl() + url;
    }

    Charset charset = hostConfig.getCharset() == null ? Consts.UTF_8 : hostConfig.getCharset();
    String stringBody = workerBuilder.getStringBody();
    File fileBody = workerBuilder.getFileBody();
    InputStream streamBody = workerBuilder.getStreamBody();
    Map<String, String> params = workerBuilder.getParameters();

    String contentType = null;

    if (responseHandler instanceof JsonResponseHandler) {
        contentType = MediaType.APPLICATION_JSON_VALUE;
    } else if (responseHandler instanceof SAXSourceResponseHandler
            || responseHandler instanceof XmlResponseHandler) {
        contentType = MediaType.APPLICATION_XML_VALUE;
    } else if (responseHandler instanceof FileResponseHandler || responseHandler instanceof ImageResponseHandler
            || responseHandler instanceof OutputStreamResponseHandler) {
        contentType = MediaType.ALL_VALUE;
    } else if (responseHandler instanceof NoResultResponseHandler) {
        contentType = ((NoResultResponseHandler) responseHandler).getContentType().getMimeType();
    } else {
        contentType = MediaType.TEXT_PLAIN_VALUE;
    }

    RequestBuilder requestBuilder = RequestBuilder.create(method).setCharset(charset).setUri(url);

    if (stringBody != null) {

        StringEntity reqEntity = new StringEntity(stringBody, charset);
        reqEntity.setContentType(contentType + ";charset=" + charset.name());
        requestBuilder.setEntity(reqEntity);

    } else if (fileBody != null || streamBody != null) {

        String filename = workerBuilder.getFilename();

        MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create().setLaxMode();

        if (fileBody != null) {
            Args.check(fileBody.isFile(), "fileBody must be a file");
            Args.check(fileBody.canRead(), "fileBody must be readable");

            if (filename == null && streamBody == null)
                filename = fileBody.getName();

            FileBody bin = new FileBody(fileBody, ContentType.APPLICATION_OCTET_STREAM,
                    streamBody != null ? fileBody.getName() : filename);
            reqEntity.addPart(workerBuilder.getFileFieldName(), bin);
        }

        Args.notEmpty(filename, "filename");

        if (streamBody != null)
            reqEntity.addBinaryBody(workerBuilder.getFileFieldName(), streamBody,
                    ContentType.APPLICATION_OCTET_STREAM, filename);

        buildParameters(reqEntity, params, charset);

        requestBuilder.setEntity(reqEntity.build());
    }

    if (fileBody == null && streamBody == null) {
        buildParameters(requestBuilder, params);
    }

    if (workerBuilder.getReadTimeout() > -1) {

        requestBuilder.setConfig(RequestConfig.copy(this.hostConfig.getRequestConfig())
                .setSocketTimeout(workerBuilder.getReadTimeout()).build());
    }

    HttpUriRequest httpRequest = ParameterRequestBuilder.build(requestBuilder);

    setAcceptHeader(httpRequest, contentType);

    if (workerBuilder.isAjax())
        setAjaxHeader(httpRequest);

    HttpClientContext context = workerBuilder.getContext();
    if (context == null)
        context = defaultHttpContext;

    T result = getHttpClient().execute(httpRequest, responseHandler, context);

    if (log.isDebugEnabled()) {
        log.debug(String.format("Send data to path:[%s]\"%s\". result: %s", method, url, result));
    }

    return result;
}

From source file:org.fcrepo.test.api.TestRESTAPI.java

protected static StringEntity getStringEntity(String content, String contentType) {
    if (content == null) {
        return null;
    }//from  w  ww .j a  va 2  s.c  o  m

    StringEntity entity = new StringEntity(content, Charset.forName("UTF-8"));
    if (contentType != null) {
        entity.setContentType(contentType);
    }
    return entity;
}

From source file:com.google.appinventor.components.runtime.FusiontablesControl.java

/**
 * Method for handling 'create table' SQL queries. At this point that is
 * the only query that we support using a POST request.
 *
 * TODO: Generalize this for other queries that require POST.
 *
 * @param query -- a query of the form "create table <json encoded content>"
 * @param authToken -- Oauth 2.0 access token
 * @return//from   ww w . j  a  v  a  2s.  c o  m
 */
private String doPostRequest(String query, String authToken) {
    org.apache.http.HttpResponse response = null;
    String jsonContent = query.trim().substring("create table".length());
    Log.i(LOG_TAG, "Http Post content = " + jsonContent);

    // Set up the POST request

    StringEntity entity = null;
    HttpPost request = new HttpPost(FUSIONTABLES_POST + "?key=" + ApiKey()); // Fusiontables Uri
    try {
        entity = new StringEntity(jsonContent);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return "Error: " + e.getMessage();
    }
    entity.setContentType("application/json");
    request.addHeader("Authorization", AUTHORIZATION_HEADER_PREFIX + authToken);
    request.setEntity(entity);

    // Execute the request

    HttpClient client = new DefaultHttpClient();
    try {
        response = client.execute(request);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        return "Error: " + e.getMessage();
    } catch (IOException e) {
        e.printStackTrace();
        return "Error: " + e.getMessage();
    }

    // Process the response
    // A valid response will have code=200 and contain a tableId value plus other stuff.
    // We just return the table id.
    int statusCode = response.getStatusLine().getStatusCode();
    if (response != null && statusCode == 200) {
        try {
            String jsonResult = FusiontablesControl.httpApacheResponseToString(response);
            JSONObject jsonObj = new JSONObject(jsonResult);
            if (jsonObj.has("tableId")) {
                queryResultStr = "tableId," + jsonObj.get("tableId");
            } else {
                queryResultStr = jsonResult;
            }

        } catch (IllegalStateException e) {
            e.printStackTrace();
            return "Error: " + e.getMessage();
        } catch (JSONException e) {
            e.printStackTrace();
            return "Error: " + e.getMessage();
        }
        Log.i(LOG_TAG, "Response code = " + response.getStatusLine());
        Log.i(LOG_TAG, "Query = " + query + "\nResultStr = " + queryResultStr);
        // queryResultStr = response.getStatusLine().toString();
    } else {
        Log.i(LOG_TAG, "Error: " + response.getStatusLine().toString());
        queryResultStr = response.getStatusLine().toString();
    }

    return queryResultStr;
}

From source file:com.liferay.petra.json.web.service.client.BaseJSONWebServiceClientImpl.java

@Override
public String doPostAsJSON(String url, String json, Map<String, String> headers)
        throws JSONWebServiceInvocationException, JSONWebServiceTransportException {

    HttpPost httpPost = new HttpPost(url);

    addHeaders(httpPost, headers);//  www .j av  a2  s .  c o m

    StringEntity stringEntity = new StringEntity(json, _CHARSET);

    stringEntity.setContentType("application/json");

    httpPost.setEntity(stringEntity);

    return execute(httpPost);
}

From source file:com.nononsenseapps.notepad.sync.googleapi.GoogleAPITalker.java

/**
 * SUpports Post and Put. Anything else will not have any effect
 * /*w ww  .  j a  va 2  s.c  o  m*/
 * @param httppost
 * @param list
 */
private void setPostBody(HttpUriRequest httppost, GoogleTaskList list) {
    StringEntity se = null;
    try {
        se = new StringEntity(list.toJSON(), HTTP.UTF_8);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    se.setContentType("application/json");
    if (httppost instanceof HttpPost)
        ((HttpPost) httppost).setEntity(se);
    else if (httppost instanceof HttpPut)
        ((HttpPut) httppost).setEntity(se);
}

From source file:org.geowebcache.jetty.RestIntegrationTest.java

private CloseableHttpResponse handlePut(URI uri, CloseableHttpClient client, String data) throws Exception {
    HttpPut request = new HttpPut(jetty.getUri().resolve(uri));
    StringEntity entity = new StringEntity(data);
    entity.setContentType(new BasicHeader("Content-type", "text/xml"));
    request.setEntity(entity);/*from  w ww  .j a v a 2 s  .c o m*/
    CloseableHttpResponse response = client.execute(request);
    return response;
}

From source file:org.geowebcache.jetty.RestIntegrationTest.java

private CloseableHttpResponse handlePost(URI uri, CloseableHttpClient client, String data) throws Exception {
    HttpPost request = new HttpPost(jetty.getUri().resolve(uri));
    StringEntity entity = new StringEntity(data);
    entity.setContentType(new BasicHeader("Content-type", "text/xml"));
    request.setEntity(entity);//  ww w  . ja v  a  2s . c om
    CloseableHttpResponse response = client.execute(request);
    return response;
}

From source file:at.ac.tuwien.dsg.comot.orchestrator.interraction.rsybl.rSYBLInterraction.java

public void sendUpdatedConfigToRSYBL(CloudService serviceTemplate,
        CompositionRulesConfiguration compositionRulesConfiguration, String effectsJSON) {

    HttpHost endpoint = new HttpHost(rSYBL_BASE_IP, rSYBL_BASE_PORT);

    {/*  w w w .ja  va2 s.  c  o m*/
        DefaultHttpClient httpClient = new DefaultHttpClient();

        try {

            JAXBContext jAXBContext = JAXBContext.newInstance(CompositionRulesConfiguration.class);

            Marshaller marshaller = jAXBContext.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

            StringWriter sw = new StringWriter();
            log.info("Sending  updated composition rules");
            marshaller.marshal(compositionRulesConfiguration, sw);
            log.info(sw.toString());

            URI putDeploymentStructureURL = UriBuilder
                    .fromPath(rSYBL_BASE_URL + "/" + serviceTemplate.getId() + "/compositionRules").build();
            HttpPost putDeployment = new HttpPost(putDeploymentStructureURL);

            StringEntity entity = new StringEntity(sw.getBuffer().toString());

            entity.setContentType("application/xml");
            entity.setChunked(true);

            putDeployment.setEntity(entity);

            log.info("Executing request " + putDeployment.getRequestLine());
            HttpResponse response = httpClient.execute(endpoint, putDeployment);
            HttpEntity resEntity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (response.getStatusLine().getStatusCode() == 200) {

            }
            if (resEntity != null) {
                System.out.println("Response content length: " + resEntity.getContentLength());
                System.out.println("Chunked?: " + resEntity.isChunked());
            }

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

    }

    {
        DefaultHttpClient httpClient = new DefaultHttpClient();

        try {

            URI putDeploymentStructureURL = UriBuilder
                    .fromPath(rSYBL_BASE_URL + "/" + serviceTemplate.getId() + "/elasticityCapabilitiesEffects")
                    .build();
            HttpPost putDeployment = new HttpPost(putDeploymentStructureURL);

            StringEntity entity = new StringEntity(effectsJSON);

            entity.setContentType("application/json");
            entity.setChunked(true);

            putDeployment.setEntity(entity);

            log.info("Send updated Effects");
            log.info(effectsJSON);

            HttpResponse response = httpClient.execute(endpoint, putDeployment);

            HttpEntity resEntity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (response.getStatusLine().getStatusCode() == 200) {

            }
            if (resEntity != null) {
                System.out.println("Response content length: " + resEntity.getContentLength());
                System.out.println("Chunked?: " + resEntity.isChunked());
            }

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

    }

    {
        DefaultHttpClient httpClient = new DefaultHttpClient();

        try {

            JAXBContext jAXBContext = JAXBContext.newInstance(CloudServiceXML.class);
            CloudServiceXML cloudServiceXML = toRSYBLRepresentation(serviceTemplate);
            Marshaller marshaller = jAXBContext.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            StringWriter sw = new StringWriter();
            log.info("Sending updated service description to rSYBL");
            marshaller.marshal(cloudServiceXML, sw);
            log.info(sw.toString());

            URI putDeploymentStructureURL = UriBuilder
                    .fromPath(rSYBL_BASE_URL + "/" + serviceTemplate.getId() + "/elasticityRequirements")
                    .build();
            HttpPost putDeployment = new HttpPost(putDeploymentStructureURL);

            StringEntity entity = new StringEntity(sw.getBuffer().toString());

            entity.setContentType("application/xml");
            entity.setChunked(true);

            putDeployment.setEntity(entity);

            log.info("Executing request " + putDeployment.getRequestLine());
            HttpResponse response = httpClient.execute(endpoint, putDeployment);
            HttpEntity resEntity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (response.getStatusLine().getStatusCode() == 200) {

            }
            if (resEntity != null) {
                System.out.println("Response content length: " + resEntity.getContentLength());
                System.out.println("Chunked?: " + resEntity.isChunked());
            }

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

    }

}