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

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

Introduction

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

Prototype

@Deprecated
    public void consumeContent() throws IOException 

Source Link

Usage

From source file:com.norman0406.slimgress.API.Interface.Interface.java

public void request(final Handshake handshake, final String requestString, final Location playerLocation,
        final JSONObject requestParams, final RequestResult result) throws InterruptedException {
    if (!handshake.isValid() || handshake.getXSRFToken().length() == 0)
        throw new RuntimeException("handshake is not valid");

    new Thread(new Runnable() {
        public void run() {

            // create post
            String postString = mApiBaseURL + mApiRequest + requestString;
            HttpPost post = new HttpPost(postString);

            // set additional parameters
            JSONObject params = new JSONObject();
            if (requestParams != null) {
                if (requestParams.has("params"))
                    params = requestParams;
                else {
                    try {
                        params.put("params", requestParams);

                        // add persistent request parameters
                        if (playerLocation != null) {
                            String loc = String.format("%08x,%08x", playerLocation.getLatitude(),
                                    playerLocation.getLongitude());
                            params.getJSONObject("params").put("playerLocation", loc);
                            params.getJSONObject("params").put("location", loc);
                        }/* w w  w  .  ja va  2  s .c om*/
                        params.getJSONObject("params").put("knobSyncTimestamp", getCurrentTimestamp());

                        JSONArray collectedEnergy = new JSONArray();

                        // TODO: add collected energy guids

                        params.getJSONObject("params").put("energyGlobGuids", collectedEnergy);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            } else {
                try {
                    params.put("params", null);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            try {
                StringEntity entity = new StringEntity(params.toString(), "UTF-8");
                entity.setContentType("application/json");
                post.setEntity(entity);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            // set header
            post.setHeader("Content-Type", "application/json;charset=UTF-8");
            post.setHeader("Accept-Encoding", "gzip");
            post.setHeader("User-Agent", "Nemesis (gzip)");
            post.setHeader("X-XsrfToken", handshake.getXSRFToken());
            post.setHeader("Host", mApiBase);
            post.setHeader("Connection", "Keep-Alive");
            post.setHeader("Cookie", "SACSID=" + mCookie);

            // execute and get the response.
            try {
                HttpResponse response = null;
                String content = null;

                synchronized (Interface.this) {
                    response = mClient.execute(post);
                    assert (response != null);

                    if (response.getStatusLine().getStatusCode() == 401) {
                        // token expired or similar
                        //isAuthenticated = false;
                        response.getEntity().consumeContent();
                    } else {
                        HttpEntity entity = response.getEntity();

                        // decompress gzip if necessary
                        Header contentEncoding = entity.getContentEncoding();
                        if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip"))
                            content = decompressGZIP(entity);
                        else
                            content = EntityUtils.toString(entity);

                        entity.consumeContent();
                    }
                }

                // handle request result
                if (content != null) {
                    JSONObject json = new JSONObject(content);
                    RequestResult.handleRequest(json, result);
                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }).start();
}

From source file:se.lu.nateko.edca.svc.GeoHelper.java

/**
 * Uploads the active layer's data to the geospatial server
 * and deletes the data from the device.
 * @return True if successful.// ww w.  ja  v  a  2s  .  c om
 */
private boolean upload() {
    Log.d(TAG, "upload() called.");
    /* Try to form an URI from the supplied ServerConnection info. */
    if (mService.getActiveServer() == null) // Cannot connect unless there is an active connection.
        return false;
    String uriString = mService.getActiveServer().getAddress() + "/wfs";
    Log.i(TAG, uriString);

    /* Post all geometry from the active layer to that layer on the geospatial server. */
    HttpResponse response;
    StringEntity se;
    boolean responseSuccessful = false;
    StringBuilder stringTotal = new StringBuilder();
    try {
        final HttpParams httpParameters = mHttpClient.getParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, TIME_OUT * 1000);
        HttpConnectionParams.setSoTimeout(httpParameters, TIME_OUT * 1000);

        se = new StringEntity(formTransactXML());
        se.setContentType("text/xml");
        HttpPost postRequest = new HttpPost(uriString);
        postRequest.setEntity(se);

        response = mHttpClient.execute(postRequest);
        InputStream xmlStream = response.getEntity().getContent();

        BufferedReader r = new BufferedReader(new InputStreamReader(xmlStream));
        String line;
        while ((line = r.readLine()) != null)
            stringTotal.append(line);

        InputStream is = new ByteArrayInputStream(stringTotal.toString().getBytes("UTF-8"));
        responseSuccessful = parseXMLResponse(is);

    } catch (UnsupportedEncodingException e) {
        Log.e(TAG, e.toString());
        return false;
    } catch (ClientProtocolException e) {
        Log.e(TAG, e.toString());
        return false;
    } catch (IOException e) {
        Log.e(TAG, e.toString());
        return false;
    }
    Log.i(TAG, "Insert Response: " + stringTotal.toString());

    try { // Consume the HttpEntity.
        se.consumeContent();
    } catch (UnsupportedOperationException e) {
        Log.e(TAG, "Operation unsupported by streaming entity sub-class: " + e.toString());
    } catch (IOException e) {
        Log.e(TAG, "Entity consumed?: " + e.toString());
        e.printStackTrace();
    }

    if (responseSuccessful) {
        /* Remove all uploaded geometry from the active layer and the local storage. */
        mGeoLayer.clearGeometry(false);

        deleteGeographyLayer(mGeoLayer.getName());

        /* Update the layer table to reflect that the layer is no longer stored on the device. */
        Cursor layerCursor = mService.getSQLhelper()
                .fetchData(LocalSQLDBhelper.TABLE_LAYER, LocalSQLDBhelper.KEY_LAYER_COLUMNS,
                        LocalSQLDBhelper.ALL_RECORDS,
                        new String(LocalSQLDBhelper.KEY_LAYER_NAME + " = \""
                                + Utilities.dropColons(mGeoLayer.getName(), Utilities.RETURN_LAST) + "\""),
                        false);
        mService.getActiveActivity().startManagingCursor(layerCursor);
        if (layerCursor.moveToFirst()) {
            long layerid = layerCursor.getInt(0);
            int layerMode = layerCursor.getInt(2);
            if (layerMode % LocalSQLDBhelper.LAYER_MODE_STORE == 0) // If the layer is currently stored, remove that mode.
                mService.getSQLhelper().updateData(LocalSQLDBhelper.TABLE_LAYER, layerid,
                        LocalSQLDBhelper.KEY_LAYER_ID, new String[] { LocalSQLDBhelper.KEY_LAYER_USEMODE },
                        new String[] { String.valueOf(layerMode / LocalSQLDBhelper.LAYER_MODE_STORE) });
        }
        return true;
    } else
        return false;

}