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.sampleapp.db.CloudantDAOFactory.java

@Override
public void delSelected(String twitterName) {
    try {/*from   w  w w .  j a v a2s  .  c om*/
        String record = getRecordAsJson(twitterName);
        JSONObject jsonObject = new JSONObject(record);
        jsonObject.put("_deleted", true);
        HttpPost post = new HttpPost(url + "/" + database);

        StringEntity parameters = new StringEntity(jsonObject.toString());
        parameters.setContentType("application/json");
        post.setEntity(parameters);
        CloseableHttpResponse response = httpClient.execute(post);
        int rc = response.getStatusLine().getStatusCode();
        if (rc == HttpStatus.SC_OK || rc == HttpStatus.SC_CREATED || rc == HttpStatus.SC_ACCEPTED) {
            String result = EntityUtils.toString(response.getEntity());
            System.out.println("Cloudant POST to delete data returned " + result);
        } else {
            System.err.println("Fatal error deleting data: " + response.getStatusLine());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:se.berazy.api.client.PoSInvoiceClient.java

/**
 * Sends a POST request./*from  w w w  .ja v a2s  .co m*/
 * 
 * @param  object
 * @throws ClientProtocolException 
 * @throws IOException 
 */
<TRequest, TResponse> TResponse sendRequest(String url, JAXBElement<TRequest> requestObject,
        Class<TResponse> responseObject) throws IOException, ClientProtocolException {
    loadProperties();
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);
    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");

    String key = EncryptionUtils.hash((getIpAddress() + formatter.format(new Date()) + getAuthToken()));
    httpPost.addHeader("accept", "application/xml");
    httpPost.addHeader("customerNo", getCustomerNo().toString());
    httpPost.addHeader("key", key);

    try {
        String data = XmlUtils.serialize(requestObject);
        StringEntity stringEntity = new StringEntity(data);
        stringEntity.setContentType("application/xml");
        stringEntity.setContentEncoding("UTF-8");
        httpPost.setEntity(stringEntity);
        log.debug(String.format("XML request: ", data));
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream instream = entity.getContent();
            try {
                InputStream is = response.getEntity().getContent();
                return XmlUtils.deserialize(is, responseObject);
            } catch (IOException e) {
                throw e;
            } catch (RuntimeException e) {
                httpPost.abort();
                throw e;
            } finally {
                try {
                    instream.close();
                } catch (Exception e) {
                    log.warn("Cannot close response stream.", e);
                }
            }
        } else {
            throw new ClientProtocolException("Response contains no content");
        }
    } catch (JAXBException e) {
        throw new ClientProtocolException("Malformed XML", e);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:msgclient.ServerConnection.java

public JSONObject makePostToServer(String path, String json_data) {
    CloseableHttpResponse response;//from w  w w . j  a  v  a  2  s . com
    JSONObject jsonObject = null;

    // Send a POST request to the server
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
        // Create a URI            
        URI uri = new URIBuilder().setScheme(PROTOCOL_TYPE).setHost(mServerName + ":" + mPort).setPath(path)
                .build();
        HttpPost httppost = new HttpPost(uri);
        //System.out.println(httppost.getURI());
        StringEntity entity = new StringEntity(json_data, ContentType.create("plain/text", "UTF-8"));
        entity.setContentType("application/json");
        httppost.setEntity(entity);

        response = httpClient.execute(httppost);
        if (response.getStatusLine().getStatusCode() == 200) {
            String jsonData = IOUtils.toString(response.getEntity().getContent());
            JSONParser parser = new JSONParser();
            Object obj = parser.parse(jsonData);
            jsonObject = (JSONObject) obj;
        } else {
            System.out.println(
                    "Received status code " + response.getStatusLine().getStatusCode() + " from server");
        }

        response.close();
        httpClient.close();
    } catch (Exception e) {
        System.out.println(e);
        return null;
    }

    return jsonObject;
}

From source file:com.paramedic.mobshaman.activities.AccessTimeActivity.java

public void postAccessTime() {

    Gson g = new Gson();
    String jsonAccessTime = g.toJson(getMobileAccessTime());
    StringEntity entity = null;
    try {//from   w  ww . ja  va 2  s  . c  om
        entity = new StringEntity(jsonAccessTime);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));

    //        URL_HC = "http://10.0.3.2/wapimobile/api/mobileaccesstime?licencia=5688923116";

    ServiciosRestClient.post(context, URL_HC, entity, "application/json", new JsonHttpResponseHandler() {
        @Override
        public void onStart() {
            String message = TipoMovimiento == 0 ? "Registrando ingreso..." : "Registrando egreso...";
            pDialog.setMessage(message);
            pDialog.show();
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
            Utils.showToast(getApplicationContext(), "Error " + statusCode + ": " + throwable.getMessage());
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
            super.onFailure(statusCode, headers, throwable, errorResponse);
            Utils.showToast(getApplicationContext(), "Error " + statusCode + ": " + throwable.getMessage());
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject result) {
            Utils.showToast(getApplicationContext(), result.toString());
            startActivity(intent);
        }

        @Override
        public void onFinish() {
            pDialog.dismiss();
        }
    });
}

From source file:com.longle1.facedetection.TimedAsyncHttpResponseHandler.java

public void executePut(String putURL, RequestParams params, JSONObject json) {
    try {//  www. ja va  2  s .co m
        AsyncHttpClient client = new AsyncHttpClient();
        StringEntity se = null;
        try {
            se = new StringEntity(json.toString());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return;
        }
        se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));

        // Add SSL
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(mContext.getResources().openRawResource(R.raw.truststore), "changeit".toCharArray());
        SSLSocketFactory sf = new SSLSocketFactory(trustStore);
        client.setSSLSocketFactory(sf);

        client.setTimeout(30000);

        client.put(null, putURL + "?" + params.toString(), se, null, this);
    } catch (Exception e) {
        e.printStackTrace();
    }
    Log.i("executePut", "done");
}

From source file:org.appcelerator.titanium.analytics.TiAnalyticsService.java

@Override
public void onStart(Intent intent, final int startId) {
    super.onStart(intent, startId);

    if (!sending.compareAndSet(false, true)) {
        Log.i(TAG, "Send already in progress, skipping intent");
    }/*from   w ww .j a  va  2s .  c om*/

    final TiAnalyticsService self = this;

    Thread t = new Thread(new Runnable() {

        public void run() {
            Log.i(TAG, "Analytics Service Started");
            try {

                if (connectivityManager == null) {
                    Log.w(TAG, "Connectivity manager not available.");
                    stopSelf(startId);
                    return;
                }
                TiAnalyticsModel model = new TiAnalyticsModel(self);
                if (!model.hasEvents()) {
                    Log.d(TAG, "No events to send.", Log.DEBUG_MODE);
                    stopSelf(startId);
                    return;
                }

                while (model.hasEvents()) {
                    if (canSend()) {
                        LinkedHashMap<Integer, JSONObject> events = model
                                .getEventsAsJSON(BUCKET_SIZE_FAST_NETWORK);

                        int len = events.size();
                        int[] eventIds = new int[len];
                        Iterator<Integer> keys = events.keySet().iterator();

                        JSONArray records = new JSONArray();
                        // build up data to send and records to delete on success
                        for (int i = 0; i < len; i++) {
                            int id = keys.next();
                            // ids are kept even on error JSON to prevent unrestrained growth
                            // and a queue blocked by bad records.
                            eventIds[i] = id;
                            records.put(events.get(id));

                            if (Log.isDebugModeEnabled()) {
                                JSONObject obj = events.get(id);
                                Log.d(TAG, "Sending event: type = " + obj.getString("type") + ", timestamp = "
                                        + obj.getString("ts"));
                            }
                        }
                        boolean deleteEvents = true;
                        if (records.length() > 0) {
                            if (Log.isDebugModeEnabled()) {
                                Log.d(TAG, "Sending " + records.length() + " analytics events.");
                            }
                            try {
                                String jsonData = records.toString() + "\n";
                                String postUrl = TiApplication.getInstance() == null ? ANALYTICS_URL
                                        : ANALYTICS_URL + TiApplication.getInstance().getAppGUID();

                                HttpPost httpPost = new HttpPost(postUrl);
                                StringEntity entity = new StringEntity(jsonData);
                                entity.setContentType("text/json");
                                httpPost.setEntity(entity);

                                HttpParams httpParams = new BasicHttpParams();
                                HttpConnectionParams.setConnectionTimeout(httpParams, 5000); //TODO use property
                                //HttpConnectionParams.setSoTimeout(httpParams, 15000); //TODO use property
                                HttpClient client = new DefaultHttpClient(httpParams);

                                ResponseHandler<String> responseHandler = new BasicResponseHandler();
                                client.getParams().setBooleanParameter("http.protocol.expect-continue", false);

                                @SuppressWarnings("unused")
                                String response = client.execute(httpPost, responseHandler);
                            } catch (Throwable t) {
                                Log.e(TAG, "Error posting events: " + t.getMessage(), t);
                                deleteEvents = false;
                                records = null;
                                break;
                            }
                        }

                        records = null;

                        if (deleteEvents) {
                            model.deleteEvents(eventIds);
                        }

                        events.clear();
                    } else {
                        Log.w(TAG, "Network unavailable, can't send analytics");
                        //TODO reset alarm?
                        break;
                    }
                }

                Log.i(TAG, "Stopping Analytics Service");
                stopSelf(startId);
            } catch (Throwable t) {
                Log.e(TAG, "Unhandled exception in analytics thread: ", t);
                stopSelf(startId);
            } finally {
                if (!sending.compareAndSet(true, false)) {
                    Log.w(TAG, "Expected to be in a sending state. Sending was already false.", Log.DEBUG_MODE);
                }
            }
        }
    });
    t.setPriority(Thread.MIN_PRIORITY);
    t.start();
}

From source file:ws.argo.responder.ProbeHandlerThread.java

/**
 * If the probe yields responses from the handler, then send this method will
 * send the responses to the given respondTo addresses.
 * /*from  w  w  w  . j av  a 2 s.c  o m*/
 * @param respondToURL - address to send the response to
 * @param payloadType - JSON or XML
 * @param payload - the actual service records to return
 * @return true if the send was successful
 */
private boolean sendResponse(String respondToURL, String payloadType, ResponseWrapper payload) {

    // This method will likely need some thought and care in the error handling
    // and error reporting
    // It's a had job at the moment.

    String responseStr = null;
    String contentType = null; // MIME type
    boolean success = true;

    switch (payloadType) {
    case "XML": {
        responseStr = payload.toXML();
        contentType = "application/xml";
        break;
    }
    case "JSON": {
        responseStr = payload.toJSON();
        contentType = "application/json";
        break;
    }
    default:
        responseStr = payload.toJSON();
    }

    try {

        HttpPost postRequest = new HttpPost(respondToURL);

        StringEntity input = new StringEntity(responseStr);
        input.setContentType(contentType);
        postRequest.setEntity(input);

        LOGGER.debug("Sending response");
        LOGGER.debug("Response payload:");
        LOGGER.debug(responseStr);
        CloseableHttpResponse httpResponse = httpClient.execute(postRequest);
        try {

            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode > 300) {
                throw new RuntimeException(
                        "Failed : HTTP error code : " + httpResponse.getStatusLine().getStatusCode());
            }

            if (statusCode != 204) {
                BufferedReader br = new BufferedReader(
                        new InputStreamReader((httpResponse.getEntity().getContent())));

                LOGGER.debug("Successful response from response target - " + respondToURL);
                String output;
                LOGGER.debug("Output from Listener .... \n");
                while ((output = br.readLine()) != null) {
                    LOGGER.debug(output);
                }
                br.close();
            }
        } finally {
            httpResponse.close();
        }

        LOGGER.info("Successfully handled probeID: " + probe.getProbeId() + " sending response to: "
                + respondToURL);

    } catch (MalformedURLException e) {
        success = false;
        LOGGER.error("MalformedURLException occured  for probeID [" + payload.getProbeID() + "]"
                + "\nThe respondTo URL was a no good.  respondTo URL is: " + respondToURL);
    } catch (IOException e) {
        success = false;
        LOGGER.error("An IOException occured for probeID [" + payload.getProbeID() + "]" + " - "
                + e.getLocalizedMessage());
        LOGGER.debug("Stack trace for IOException for probeID [" + payload.getProbeID() + "]", e);
    } catch (Exception e) {
        success = false;
        LOGGER.error("Some other error occured for probeID [" + payload.getProbeID() + "]"
                + ".  respondTo URL is: " + respondToURL + " - " + e.getLocalizedMessage());
        LOGGER.debug("Stack trace for probeID [" + payload.getProbeID() + "]", e);
    }

    return success;

}

From source file:com.sampleapp.db.CloudantDAOFactory.java

@Override
public void saveData(Influencer influencer) {
    // check whether the document is present in the database
    // if not present just insert new doc or else just update the existing
    // doc./* w  w w.j  a va  2 s.  c  o m*/
    try {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("_id", influencer.getTwitterHandle());
        jsonObject.put("mcount", influencer.getMcount());
        jsonObject.put("fcount", influencer.getFcount());
        jsonObject.put("fscore", influencer.getFscore());
        jsonObject.put("rtcount", influencer.getRtcount());
        jsonObject.put("rtscore", influencer.getRtscore());
        jsonObject.put("totalscore", influencer.getTotalscore());
        HttpPost post = new HttpPost(url + "/" + database);
        System.out.println("New data: " + jsonObject.toString());
        StringEntity parameters = new StringEntity(jsonObject.toString());
        parameters.setContentType("application/json");
        post.setEntity(parameters);
        CloseableHttpResponse response = httpClient.execute(post);
        int rc = response.getStatusLine().getStatusCode();
        if (rc == HttpStatus.SC_OK || rc == HttpStatus.SC_CREATED || rc == HttpStatus.SC_ACCEPTED) {
            String result = EntityUtils.toString(response.getEntity());
            System.out.println("Cloudant POST to add new data returned " + result);
        } else {
            System.err.println("Fatal error saving data: " + response.getStatusLine());
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:org.mule.modules.apifortress.ApiFortressClient.java

private String run(String url, String body) throws IOException {
    final HttpPost post = new HttpPost(url);
    final StringEntity entity = new StringEntity(body);
    entity.setContentType(CT_APPLICATION_JSON);
    post.setEntity(entity);/*ww w. j  a va 2 s  .  c  om*/
    final HttpResponse response = client.execute(post);
    final int statusCode = response.getStatusLine().getStatusCode();

    final HttpEntity responseEntity = response.getEntity();
    final InputStream is = responseEntity.getContent();
    final String dataBack = IOUtils.toString(is);
    is.close();
    EntityUtils.consume(responseEntity);

    /**
     * failure when test execution has been rejected for some reason
     */
    if (statusCode != 200) {
        throw new ApiFortressIOException("Test execution unsuccessful. Status code=" + statusCode);
    }

    return dataBack;
}

From source file:net.benmoran.affectsampler.datastore.AppEngineClientImpl.java

public HttpResponse postJSON(URI uri, String body) throws SyncException {
    if (!isLoggedIn()) {
        login();//  w  ww .j  av  a2  s.  co  m
    }
    HttpPost request;
    try {
        request = new HttpPost(getFullURI(uri.toString()));
    } catch (URISyntaxException e) {
        throw new SyncException(e);
    }
    StringEntity entity;
    try {
        entity = new StringEntity(body);
    } catch (UnsupportedEncodingException e) {
        throw new SyncException(e);
    }
    entity.setContentType("application/json");

    request.setEntity(entity);

    Log.i(TAG, "Sending to uri " + request.getURI().toString() + " " + body);
    try {
        return mClient.execute(request);
    } catch (ClientProtocolException e) {
        throw new SyncException(e);
    } catch (IOException e) {
        throw new SyncException(e);
    }
}