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:org.piwik.sdk.TrackerBulkURLProcessor.java

public boolean doPost(URL url, JSONObject json) {
    if (url == null || json == null) {
        return false;
    }//  w  w w. j a va  2 s  . c  o  m

    String jsonBody = json.toString();

    try {
        HttpPost post = new HttpPost(url.toURI());
        StringEntity se = new StringEntity(jsonBody);
        se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        post.setEntity(se);

        return doRequest(post, jsonBody);
    } catch (URISyntaxException e) {
        Log.w(Tracker.LOGGER_TAG, String.format("URI Syntax Error %s", url.toString()), e);
    } catch (UnsupportedEncodingException e) {
        Log.w(Tracker.LOGGER_TAG, String.format("Unsupported Encoding %s", jsonBody), e);
    }

    return false;
}

From source file:com.wso2telco.transaction.log.TransactionLoggerImpl.java

public int logTransaction(Transactions transactions, String contextId) {

    //      boolean status = false;

    MobileConnectConfig.GSMAExchangeConfig gsmaExchangeConfig = configurationService.getDataHolder()
            .getMobileConnectConfig().getGsmaExchangeConfig();

    String batchId = contextId;/*from   w  ww.j  a  v  a  2 s.c  o m*/
    String path = "/v1/exchange/organizations/" + gsmaExchangeConfig.getOrganization() + "/transactions/"
            + batchId;
    String requestValidationExchangeEndpoint = "http://" + gsmaExchangeConfig.getServingOperatorHost() + path;

    HttpClient client = new DefaultHttpClient();
    HttpPost postRequest = new HttpPost(requestValidationExchangeEndpoint);

    postRequest.addHeader("Authorization", "Basic " + gsmaExchangeConfig.getAuthToken());
    postRequest.addHeader("Content-Type", "application/json");
    postRequest.addHeader("Accept", "application/json");

    // Prepare json input.
    LogRequest request = new LogRequest();
    request.setTransactions(transactions);

    Gson gson = new GsonBuilder().serializeNulls().create();
    String reqString = gson.toJson(request);

    int statusCode = -1;
    try {
        StringEntity input = new StringEntity(reqString);
        input.setContentType("application/json");
        postRequest.setEntity(input);

        HttpResponse response = client.execute(postRequest);
        statusCode = response.getStatusLine().getStatusCode();
        //           status = (statusCode == HttpStatus.SC_OK);

    } catch (ClientProtocolException e) {
        log.error(e);
        return statusCode;

    } catch (IOException e) {
        log.error(e);
        return statusCode;
    }

    //      return status;
    return statusCode;
}

From source file:org.apache.camel.component.cxf.jaxrs.CxfRsRouterTest.java

@Test
public void testPutConsumer() throws Exception {
    HttpPut put = new HttpPut(
            "http://localhost:" + getPort() + "/CxfRsRouterTest/route/customerservice/customers");
    StringEntity entity = new StringEntity(PUT_REQUEST, "ISO-8859-1");
    entity.setContentType("text/xml; charset=ISO-8859-1");
    put.setEntity(entity);//from w  w  w.  j a v  a 2s .co m
    HttpClient httpclient = new DefaultHttpClient();

    try {
        HttpResponse response = httpclient.execute(put);
        assertEquals(200, response.getStatusLine().getStatusCode());
        assertEquals("", EntityUtils.toString(response.getEntity()));
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:com.mnxfst.testing.activities.http.SOAPRequestActivity.java

/**
 * @see com.mnxfst.testing.activities.TSPlanActivity#execute(java.util.Map)
 *//*from w ww.j  a  v a2s .com*/
public TSPlanExecutionContext execute(TSPlanExecutionContext ctx) throws TSPlanActivityExecutionException {

    // replace payload variables with values fetched from context
    String payload = new String(this.payloadTemplate);

    for (String logPattern : payloadVariables.keySet()) {
        String replacementPattern = payloadVariables.get(logPattern);
        Object ctxValue = null;
        try {
            ctxValue = ctx.evaluate(logPattern);
        } catch (TSVariableEvaluationFailedException e) {
            throw new TSPlanActivityExecutionException("Failed to evaluate " + logPattern);
        }

        if (ctxValue != null)
            payload = payload.replaceAll(replacementPattern, ctxValue.toString());

    }

    ctx.addContextValue(contextExportVariableRequestInput, payload, ExecutionContextValueType.RUN);

    // convert payload into request entity and assign it
    StringEntity entity = null;
    try {
        entity = new StringEntity(payload, payloadEncoding);
        entity.setContentType("text/xml");
    } catch (UnsupportedEncodingException e) {
        throw new TSPlanActivityExecutionException(
                "Failed to assign configured payload to post request. Error: " + e.getMessage(), e);
    }
    try {
        HttpResponse response = sendPOSTRequest(entity, header);
        String content = EntityUtils.toString(response.getEntity());
        ctx.addContextValue(contextExportVariableResponseContent, content, ExecutionContextValueType.RUN);
    } catch (IOException e) {
        logger.error("Error found while accessing remote server: " + e.getMessage(), e);
    }

    return ctx;
}

From source file:org.mobiletrial.license.connect.RestClient.java

public void post(final String path, final JSONObject requestJson, final OnRequestFinishedListener listener) {
    Thread t = new Thread() {
        public void run() {
            Looper.prepare(); //For Preparing Message Pool for the child Thread

            // Register Schemes for http and https
            final SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            schemeRegistry.register(new Scheme("https", createAdditionalCertsSSLSocketFactory(), 443));

            final HttpParams params = new BasicHttpParams();
            final ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
            HttpClient client = new DefaultHttpClient(cm, params);

            HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit

            HttpResponse response;/*from  www  .j  av a2 s  . c  om*/
            try {
                String urlStr = mServiceUrl.toExternalForm();
                if (urlStr.charAt(urlStr.length() - 1) != '/')
                    urlStr += "/";
                urlStr += path;
                URI actionURI = new URI(urlStr);

                HttpPost post = new HttpPost(actionURI);
                StringEntity se = new StringEntity(requestJson.toString());
                se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                post.setEntity(se);
                response = client.execute(post);

                /* Checking response */
                if (response == null) {
                    listener.gotError(ERROR_CONTACTING_SERVER);
                    Log.w(TAG, "Error contacting licensing server.");
                    return;
                }
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode != HttpStatus.SC_OK) {
                    Log.w(TAG, "An error has occurred on the licensing server.");
                    listener.gotError(ERROR_SERVER_FAILURE);
                    return;
                }

                /* Convert response to JSON */
                InputStream in = response.getEntity().getContent(); //Get the data in the entity
                String responseStr = inputstreamToString(in);
                listener.gotResponse(responseStr);

            } catch (ClientProtocolException e) {
                Log.w(TAG, "ClientProtocolExeption:  " + e.getLocalizedMessage());
                e.printStackTrace();
            } catch (IOException e) {
                Log.w(TAG, "Error on contacting server: " + e.getLocalizedMessage());
                listener.gotError(ERROR_CONTACTING_SERVER);
            } catch (URISyntaxException e) {
                //This shouldn't happen   
                Log.w(TAG, "Could not build URI.. Your service Url is propably not a valid Url:  "
                        + e.getLocalizedMessage());
                e.printStackTrace();
            }
            Looper.loop(); //Loop in the message queue
        }
    };
    t.start();
}

From source file:org.alfresco.provision.BMService.java

/**
 * Populate HTTP message call with given content.
 * //from   ww  w .ja  v  a  2  s.  c o m
 * @param json
 *            {@link JSONObject} content
 * @return {@link StringEntity} content.
 * @throws UnsupportedEncodingException
 *             if unsupported
 */
public StringEntity setMessageBody(final JSONObject json) throws UnsupportedEncodingException {
    if (json == null || json.toString().isEmpty())
        throw new UnsupportedOperationException("JSON Content is required.");

    StringEntity se = setMessageBody(json.toString());
    se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, MIME_TYPE_JSON));
    return se;
}

From source file:org.apache.camel.itest.osgi.cxf.blueprint.CxfRsBlueprintRouterTest.java

@Test
public void testPutConsumer() throws Exception {
    HttpPut put = new HttpPut("http://localhost:9000/route/customerservice/customers");
    StringEntity entity = new StringEntity(PUT_REQUEST, "ISO-8859-1");
    entity.setContentType("text/xml; charset=ISO-8859-1");
    put.setEntity(entity);/*from  w  w  w.j  a  v a 2  s . c  om*/
    HttpClient httpclient = new DefaultHttpClient();

    try {
        HttpResponse response = httpclient.execute(put);
        assertEquals(200, response.getStatusLine().getStatusCode());
        assertEquals("", EntityUtils.toString(response.getEntity()));
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:org.ckan.Connection.java

/**
* Makes a POST request/*w ww . j  ava2s . c o  m*/
*
* Submits a POST HTTP request to the CKAN instance configured within
* the constructor, returning the entire contents of the response.
*
* @param  path The URL path to make the POST request to
* @param  data The data to be posted to the URL
* @returns The String contents of the response
* @throws A CKANException if the request fails
*/
protected String post(String path, String data) throws CKANException {
    URL url = null;

    try {
        url = new URL(this.m_host + ":" + this.m_port + path);
    } catch (MalformedURLException mue) {
        System.err.println(mue);
        return null;
    }

    String body = "";

    BasicClientConnectionManager bccm = null;
    ClientConnectionManager cm = null;
    try {
        /***********************************************************************/
        SSLContext sslContext = SSLContext.getInstance("SSL");
        // set up a TrustManager that trusts everything
        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                System.out.println("getAcceptedIssuers =============");
                return null;
            }

            public void checkClientTrusted(X509Certificate[] certs, String authType) {
                System.out.println("checkClientTrusted =============");
            }

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
                System.out.println("checkServerTrusted =============");
            }
        } }, new SecureRandom());
        SSLSocketFactory sf = new SSLSocketFactory(sslContext);
        Scheme httpsScheme = new Scheme("https", 443, sf);
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(httpsScheme);
        //bccm = new BasicClientConnectionManager(schemeRegistry);
        // apache HttpClient version >4.2 should use BasicClientConnectionManager
        cm = new SingleClientConnManager(schemeRegistry);
        /***********************************************************************/
    } catch (KeyManagementException kme) {
        System.out.println("Con ex: " + kme.getMessage());
    } catch (NoSuchAlgorithmException nsae) {
        System.out.println("Con ex: " + nsae.getMessage());
    }

    //HttpClient httpclient = new DefaultHttpClient(cm);
    HttpClient httpclient = new DefaultHttpClient();
    try {
        HttpPost postRequest = new HttpPost(url.toString());
        postRequest.setHeader("X-CKAN-API-Key", this._apikey);

        StringEntity input = new StringEntity(data);
        input.setContentType("application/json");
        postRequest.setEntity(input);

        HttpResponse response = httpclient.execute(postRequest);
        int statusCode = response.getStatusLine().getStatusCode();

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        String line = "";
        while ((line = br.readLine()) != null) {
            body += line;
        }
    } catch (IOException ioe) {
        System.out.println(ioe);
    } finally {
        httpclient.getConnectionManager().shutdown();
    }

    return body;
}

From source file:com.thistech.spotlink.engine.AbstractPlacementDecisionEngine.java

/**
 * Build an HttpPost with the//from  www.  j a v  a2  s .  c  om
 * @param body The body
 * @return The HttpPost
 */
protected HttpPost buildHttpPost(Object body) {
    HttpPost post = new HttpPost(getEndpoint());
    post.setHeader("Content-type", "application/xml");
    post.setHeader("accept", "application/xml");

    try {
        if (!(body instanceof String)) {
            body = XmlUtil.marshalToString(this.getJaxbContext(), body);
        }
        // freewheel requests need namespace removed
        body = StringUtils.replace((String) body, "fwns:", "");
        log.info(String.format("request body: %s", body));
        StringEntity bodyEntity = new StringEntity((String) body);
        bodyEntity.setContentType("text/xml");
        post.setEntity(bodyEntity);
        return post;
    } catch (Exception e) {
        throw new SpotLinkException(e);
    }
}

From source file:com.subgraph.vega.ui.httpviewer.entity.HttpEntityTextViewer.java

private HttpEntity createEntityForDocument(IDocument document) {
    try {/*from ww  w . j  ava  2  s  .  co  m*/
        final StringEntity entity = new StringEntity(document.get());
        if (currentContentType != null && !currentContentType.isEmpty()) {
            entity.setContentType(currentContentType);
        }
        if (currentContentEncoding != null && !currentContentEncoding.isEmpty()) {
            entity.setContentEncoding(currentContentEncoding);
        }
        return entity;
    } catch (UnsupportedEncodingException e) {
        throw new IllegalArgumentException("Failed to create entity from document", e);
    }
}