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

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

Introduction

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

Prototype

public InputStream getContent() throws IOException 

Source Link

Usage

From source file:com.betfair.testing.utils.cougar.manager.CougarManagerTest.java

@Test
public void sendPostRestRequest_Test() throws ParserConfigurationException, SAXException, IOException {

    String POSTQUERY = "<ComplexObject><name>sum</name><value1>7</value1><value2>75</value2></ComplexObject>";

    //String expRestXMLRequestBody = "<ComplexObject xmlns=\"http://www.betfair.com/servicetypes/v2/Baseline/\"><name>sum</name><value1>7</value1><value2>75</value2></ComplexObject>";
    String operationName = "someOperation";
    String requestWrapper = "SomeOperationRequest";

    String expRestXMLRequestBody = "<" + requestWrapper
            + " xmlns=\"http://www.betfair.com/servicetypes/v2/Baseline/\"><complexObject><name>sum</name><value1>7</value1><value2>75</value2></complexObject></"
            + requestWrapper + ">";

    //String expRestJSONRequestBody = "{\"name\":\"sum\",\"value1\":7,\"value2\":75}" ;
    String expRestJSONRequestBody = "{\"complexObject\":{\"name\":\"sum\",\"value1\":7,\"value2\":75}}";

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.parse(new InputSource(new StringReader(POSTQUERY)));

    HttpCallBean httpCallBean = new HttpCallBean();

    httpCallBean.setOperationName(operationName);
    httpCallBean.setServiceName("Baseline");
    httpCallBean.setVersion("v2");
    httpCallBean.setQueryParams(null);//ww w . j av  a2 s.  c  o m
    httpCallBean.setHeaderParams(null);

    httpCallBean.setRestPostQueryObjects(document);

    cougarManager.makeRestCougarHTTPCalls(httpCallBean);

    List<HttpUriRequest> methodsSent = cougarTestDAO.methods;

    HttpPost methodSent;

    methodSent = (HttpPost) methodsSent.get(0);

    assertNull(methodSent.getURI().getQuery());

    assertEquals("/Baseline/v2/" + operationName, methodSent.getURI().getPath());

    Header[] headers = methodSent.getAllHeaders();
    assertEquals(4, headers.length);

    assertEquals("Content-Type: application/json", String.valueOf(headers[0]));
    assertEquals("User-Agent: java/socket", String.valueOf(headers[1]));
    assertEquals("Accept: application/json", String.valueOf(headers[2]));
    //Changed this from 37...
    //assertEquals("Content-Length: 55", String.valueOf(headers[3]));
    assertEquals("X-Forwarded-For: 87.248.113.14", String.valueOf(headers[3]));

    StringEntity stringRequestEntity = (StringEntity) methodSent.getEntity();
    InputStream inputStream = stringRequestEntity.getContent();
    byte[] buffer = new byte[inputStream.available()];
    int offset = 0;
    int read;
    while ((read = inputStream.read(buffer, offset, inputStream.available())) != -1) {
        offset += read;
    }
    assertEquals(expRestJSONRequestBody, new String(buffer, "UTF-8"));

    methodSent = (HttpPost) methodsSent.get(2);

    assertNull(methodSent.getURI().getQuery());

    assertEquals("/Baseline/v2/" + operationName, methodSent.getURI().getPath());

    headers = methodSent.getAllHeaders();
    assertEquals(4, headers.length);

    stringRequestEntity = (StringEntity) methodSent.getEntity();
    inputStream = stringRequestEntity.getContent();
    buffer = new byte[inputStream.available()];
    offset = 0;
    while ((read = inputStream.read(buffer, offset, inputStream.available())) != -1) {
        offset += read;
    }
    assertEquals(expRestXMLRequestBody, new String(buffer, "UTF-8"));

    assertEquals("Content-Type: application/xml", String.valueOf(headers[0]));
    assertEquals("User-Agent: java/socket", String.valueOf(headers[1]));
    assertEquals("Accept: application/xml", String.valueOf(headers[2]));

    //assertEquals("Content-Length: 141", String.valueOf(headers[3]));
    //assertEquals("Content-Length: 186", String.valueOf(headers[3]));

    assertEquals("X-Forwarded-For: 87.248.113.14", String.valueOf(headers[3]));

}

From source file:com.clutch.ClutchAPIClient.java

private static void sendRequest(String url, boolean post, JSONObject payload, String version,
        final ClutchAPIResponseHandler responseHandler) {
    BasicHeader[] headers = { new BasicHeader("X-App-Version", version),
            new BasicHeader("X-UDID", ClutchUtils.getUDID()), new BasicHeader("X-API-Version", VERSION),
            new BasicHeader("X-App-Key", appKey), new BasicHeader("X-Bundle-Version", versionName),
            new BasicHeader("X-Platform", "Android"), };
    StringEntity entity = null;
    try {/*from w ww.  j  a v a2s.  c o m*/
        entity = new StringEntity(payload.toString());
    } catch (UnsupportedEncodingException e) {
        Log.e(TAG, "Could not encode the JSON payload and attach it to the request: " + payload.toString());
        return;
    }
    HttpRequestBase request = null;
    if (post) {
        request = new HttpPost(url);
        ((HttpEntityEnclosingRequestBase) request).setEntity(entity);
        request.setHeaders(headers);
    } else {
        request = new HttpGet(url);
    }

    class StatusCodeAndResponse {
        public int statusCode;
        public String response;

        public StatusCodeAndResponse(int statusCode, String response) {
            this.statusCode = statusCode;
            this.response = response;
        }
    }

    new AsyncTask<HttpRequestBase, Void, StatusCodeAndResponse>() {
        @Override
        protected StatusCodeAndResponse doInBackground(HttpRequestBase... requests) {
            try {
                HttpResponse resp = client.execute(requests[0]);

                HttpEntity entity = resp.getEntity();
                InputStream inputStream = entity.getContent();

                ByteArrayOutputStream content = new ByteArrayOutputStream();

                int readBytes = 0;
                byte[] sBuffer = new byte[512];
                while ((readBytes = inputStream.read(sBuffer)) != -1) {
                    content.write(sBuffer, 0, readBytes);
                }

                inputStream.close();

                String response = new String(content.toByteArray());

                content.close();

                return new StatusCodeAndResponse(resp.getStatusLine().getStatusCode(), response);
            } catch (IOException e) {
                if (responseHandler instanceof ClutchAPIDownloadResponseHandler) {
                    ((ClutchAPIDownloadResponseHandler) responseHandler).onFailure(e, "");
                } else {
                    responseHandler.onFailure(e, null);
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(StatusCodeAndResponse resp) {
            if (responseHandler instanceof ClutchAPIDownloadResponseHandler) {
                if (resp.statusCode == 200) {
                    ((ClutchAPIDownloadResponseHandler) responseHandler).onSuccess(resp.response);
                } else {
                    ((ClutchAPIDownloadResponseHandler) responseHandler).onFailure(null, resp.response);
                }
            } else {
                if (resp.statusCode == 200) {
                    responseHandler.handleSuccessMessage(resp.response);
                } else {
                    responseHandler.handleFailureMessage(null, resp.response);
                }
            }
        }
    }.execute(request);
}

From source file:de.hska.ld.core.client.ClientRequest.java

protected void processResponse(StringEntity entity) throws RequestStatusNotOKException {
    if (this.getResponseStatusCode() != HttpStatus.OK) {
        if (expectedHttpStatuscodes == null
                || !expectedHttpStatuscodes.contains(this.getResponseStatusCode())) {
            if (entity != null) {
                try {
                    InputStream inputStream = entity.getContent();
                    StringWriter writer = new StringWriter();
                    IOUtils.copy(inputStream, writer, "UTF-8");
                    String entityString = writer.toString();
                    this.exceptionLogger
                            .log(this.getLoggingPrefix() + this.action,
                                    "HTTPStatus=" + this.getResponseStatusCode().toString() + ", url="
                                            + this.url + ", entityString=" + entityString,
                                    "Client request failed!");
                } catch (Exception e) {
                    this.exceptionLogger.log(this.getLoggingPrefix() + this.action,
                            "HTTPStatus=" + this.getResponseStatusCode().toString() + ", url=" + this.url,
                            "Client request failed!");
                }//from   w ww  .  j  a  v a2s .  c  o  m
            } else {
                this.exceptionLogger.log(this.getLoggingPrefix() + this.action,
                        "HTTPStatus=" + this.getResponseStatusCode().toString() + ", url=" + this.url,
                        "Client request failed!");
            }
            throw new RequestStatusNotOKException(this.getResponseStatusCode(),
                    this.response.getStatusLine().getReasonPhrase());
        }
    }
    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);
        }
        String resultString = result.toString();
        if (resultString.contains("\"error_description\":\"Invalid access token:")) {
            throw new ValidationException("access token is invalid");
        }
        this.unparsedBody = resultString;
    } catch (IOException e) {
        this.exceptionLogger.log(this.getLoggingPrefix() + this.action, e,
                "Parsing client request failed! (1)");
    } finally {
        if (rd != null) {
            try {
                rd.close();
            } catch (IOException e) {
                //
            }
        }
    }
}

From source file:ch.admin.hermes.etl.load.SharePoint2010RESTClient.java

/**
 * LowLevel: Schreibt Daten im JSON Format. Die Daten muessen korrekt aufbereitet sein.
 * @param uri - URI ab Seite beginnend mit /_api/...
 * @param data Daten welche geschrieben werden sollen, darf null sein
 * @return body welcher der Remote Host zurueckgibt
 * @throws IOException Allgemeiner I/O Fehler
 *///from  w  w w .ja  v  a  2  s. c o  m
protected String post(String uri, String data) throws IOException {
    HttpPost request = new HttpPost(remote + uri);
    request.addHeader("Accept", "application/json;odata=verbose;charset=utf-8");
    request.addHeader("Content-Type", "application/json;odata=verbose;charset=utf-8");

    if (data != null) {
        StringEntity entity = new StringEntity(data, "UTF-8");
        request.setEntity(entity);
    }

    HttpResponse response = client.execute(request);
    checkError(response, uri);

    HttpEntity entity = response.getEntity();
    BufferedReader isr = new BufferedReader(new InputStreamReader(entity.getContent()));

    StringBuffer str = new StringBuffer();
    String line = "";
    while ((line = isr.readLine()) != null)
        str.append(line);

    EntityUtils.consume(entity);
    return (str.toString());
}

From source file:com.mollie.api.MollieClient.java

/**
 * Perform a http call. This method is used by the resource specific classes.
 * Please use the payments() method to perform operations on payments.
 *
 * @param method the http method to use//from www.  java2 s  . co  m
 * @param apiMethod the api method to call
 * @param httpBody the contents to send to the server.
 * @return result of the http call
 * @throws MollieException when the api key is not set or when there is a
 * problem communicating with the mollie server.
 * @see #performHttpCall(String method, String apiMethod)
 */
public String performHttpCall(String method, String apiMethod, String httpBody) throws MollieException {
    URI uri = null;
    String result = null;

    if (_apiKey == null || _apiKey.trim().equals("")) {
        throw new MollieException("You have not set an api key. Please use setApiKey() to set the API key.");
    }

    try {
        URIBuilder ub = new URIBuilder(this._apiEndpoint + "/" + API_VERSION + "/" + apiMethod);
        uri = ub.build();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }

    if (uri != null) {
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        HttpRequestBase action = null;
        HttpResponse response = null;

        if (method.equals(HTTP_POST)) {
            action = new HttpPost(uri);
        } else if (method.equals(HTTP_DELETE)) {
            action = new HttpDelete(uri);
        } else {
            action = new HttpGet(uri);
        }

        if (httpBody != null && action instanceof HttpPost) {
            StringEntity entity = new StringEntity(httpBody, ContentType.APPLICATION_JSON);
            ((HttpPost) action).setEntity(entity);
        }

        action.setHeader("Authorization", "Bearer " + this._apiKey);
        action.setHeader("Accept", ContentType.APPLICATION_JSON.getMimeType());

        try {
            response = httpclient.execute(action);

            HttpEntity entity = response.getEntity();
            StringWriter sw = new StringWriter();

            IOUtils.copy(entity.getContent(), sw, "UTF-8");
            result = sw.toString();
            EntityUtils.consume(entity);
        } catch (Exception e) {
            throw new MollieException("Unable to communicate with Mollie");
        }

        try {
            httpclient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return result;
}

From source file:com.cloudera.flume.handlers.hive.MarkerStore.java

public boolean sendESQuery(String elasticSearchUrl, String sb) {
    boolean success = true;
    LOG.info("sending batched stringentities");
    LOG.info("elasticSearchUrl: " + elasticSearchUrl);
    try {/*from  w  w w  . j  av  a  2s. c  om*/

        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(elasticSearchUrl);
        StringEntity se = new StringEntity(sb);

        httpPost.setEntity(se);
        HttpResponse hr = httpClient.execute(httpPost);

        LOG.info("HTTP Response: " + hr.getStatusLine());
        LOG.info("Closing httpConnection");
        httpClient.getConnectionManager().shutdown();
        LOG.info("booooooo: " + CharStreams.toString(new InputStreamReader(se.getContent())));
    } catch (IOException e) {
        e.printStackTrace();
        success = false;
    } finally {
        if (!success) {
            LOG.info("ESQuery wasn't successful, writing to markerfolder");
            writeElasticSearchToMarkerFolder(new StringBuilder(sb));
        }
    }
    LOG.info("ESQuery was successful, yay!");
    return success;

}

From source file:ch.admin.hermes.etl.load.SharePointRESTClient.java

/**
 * LowLevel: Schreibt Daten im JSON Format. Die Daten muessen korrekt aufbereitet sein.
 * @param uri - URI ab Seite beginnend mit /_api/...
 * @param data Daten welche geschrieben werden sollen, darf null sein
 * @return body welcher der Remote Host zurueckgibt
 * @throws IOException Allgemeiner I/O Fehler
 *//*from ww w  . java  2 s  .  c om*/
public String post(String uri, String data) throws IOException {
    HttpPost request = new HttpPost(remote + uri);
    request.addHeader("Accept", "application/json;odata=verbose;charset=utf-8");
    request.addHeader("Content-Type", "application/json;odata=verbose;charset=utf-8");

    if (xRequestDigest != null)
        request.addHeader("X-RequestDigest", xRequestDigest);

    if (data != null) {
        StringEntity entity = new StringEntity(data, "UTF-8");
        request.setEntity(entity);
    }

    HttpResponse response = client.execute(request);
    checkError(response, uri);

    HttpEntity entity = response.getEntity();
    BufferedReader isr = new BufferedReader(new InputStreamReader(entity.getContent()));

    StringBuffer str = new StringBuffer();
    String line = "";
    while ((line = isr.readLine()) != null)
        str.append(line);

    EntityUtils.consume(entity);
    return (str.toString());
}

From source file:com.sandklef.coachapp.http.HttpAccess.java

private String sendHttpPost(String token, StringEntity data, String header, String path)
        throws HttpAccessException {
    HttpClient client = new DefaultHttpClient();
    String url = urlBase + path;//from   w w  w .j  ava 2s.  c  o m
    HttpResponse resp = null;
    String response = null;
    Log.d(LOG_TAG, "sendHttpPost()  url:     " + urlBase);
    Log.d(LOG_TAG, "sendHttpPost()  path:    " + path);
    Log.d(LOG_TAG, "sendHttpPost()  url:     " + url);
    Log.d(LOG_TAG, "sendHttpPost()  club:    " + LocalStorage.getInstance().getCurrentClub());
    Log.d(LOG_TAG, "sendHttpPost()  header: " + header);
    try {
        Log.d(LOG_TAG, "sendHttpPost()  data:   " + data.getContent().toString());
    } catch (Exception e) {
        ;
    }

    HttpPost httpPost = new HttpPost(url);
    try {
        httpPost.setHeader(HttpSettings.CONTENT_STATUS, header);
        httpPost.setEntity(data);
        if (token != null) {
            httpPost.setHeader("X-Token", token);
            httpPost.setHeader("X-instance", LocalStorage.getInstance().getCurrentClub());
            Log.d(LOG_TAG, "Using token: " + token);
        } else {
            Log.d(LOG_TAG, "Not using token");
        }
        resp = client.execute(httpPost);
        Log.d(LOG_TAG, resp + "  <==  sendHttpPost");
        Log.d(LOG_TAG, resp.getStatusLine().getStatusCode() + "  <==  sendHttpPost");
        if (HttpSettings.isResponseOk(resp.getStatusLine().getStatusCode())) {
            Log.d(LOG_TAG, " server response ok, returning data");
            response = EntityUtils.toString(resp.getEntity());
        } else {
            Log.d(LOG_TAG, "Server response OK but bad password");
            HttpAccessException e = new HttpAccessException("sendHttpPost failed",
                    HttpAccessException.ACCESS_ERROR);
            Log.d(LOG_TAG, "Will throw: " + e.getMode());
            throw e;
        }
    } catch (IOException e) {
        throw new HttpAccessException("sendHttpPost failed", e, HttpAccessException.NETWORK_ERROR);
    }

    try {
        Log.d(LOG_TAG, " consuming entity");
        if (resp.getEntity() != null) {
            resp.getEntity().consumeContent();
        }
    } catch (IOException ex) {
        throw new HttpAccessException("sendHttpPost failed", ex, HttpAccessException.NETWORK_ERROR);
    }

    return response;
}

From source file:org.ebayopensource.twin.TwinConnection.java

@SuppressWarnings("unchecked")
private Map<String, Object> _request(String method, String path, Map<String, Object> body,
        JSONRecognizer... recognizers) throws IOException, TwinException {
    String uri = url + path;//from   w  w w  .ja  v a  2 s .com
    HttpRequest request;
    if (body == null) {
        BasicHttpRequest r = new BasicHttpRequest(method, uri);
        request = r;
    } else {
        BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest(method, uri);
        StringEntity entity;
        try {
            entity = new StringEntity(JSON.encode(body), "utf-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        entity.setContentType("application/json; charset=utf-8");
        r.setEntity(entity);
        request = r;
    }

    HttpClient client = getClient();
    try {
        HttpResponse response = client.execute(new HttpHost(url.getHost(), url.getPort()), request);
        HttpEntity entity = response.getEntity();
        if (entity == null)
            return null;
        String contentType = entity.getContentType().getValue();
        boolean isJson = (contentType != null)
                && ("application/json".equals(contentType) || contentType.startsWith("application/json;"));
        String result = null;

        InputStream in = entity.getContent();
        try {
            Reader r = new InputStreamReader(in, "UTF-8");
            StringBuilder sb = new StringBuilder();
            char[] buf = new char[256];
            int read;
            while ((read = r.read(buf, 0, buf.length)) >= 0)
                sb.append(buf, 0, read);
            r.close();

            result = sb.toString();
        } finally {
            try {
                in.close();
            } catch (Exception e) {
            }
        }

        int code = response.getStatusLine().getStatusCode();
        if (code >= 400) {
            if (isJson) {
                try {
                    throw deserializeException((Map<String, Object>) JSON.decode(result));
                } catch (IllegalArgumentException e) {
                    throw TwinError.UnknownError.create("Couldn't parse error response: \n" + result, e);
                }
            }
            if (code == 404)
                throw TwinError.UnknownCommand.create("Got server response " + code + " for request " + uri);
            else
                throw TwinError.UnknownError
                        .create("Got server response " + code + " for request " + uri + "\nBody is " + result);
        }

        if (!isJson)
            throw TwinError.UnknownError.create(
                    "Got wrong content type " + contentType + " for request " + uri + "\nBody is " + result);

        try {
            return (Map<String, Object>) JSON.decode(result, recognizers);
        } catch (Exception e) {
            throw TwinError.UnknownError
                    .create("Malformed JSON result for request " + uri + ": \nBody is " + result, e);
        }
    } catch (ClientProtocolException e) {
        throw new IOException(e);
    }
}

From source file:com.pennassurancesoftware.tutum.client.TutumClient.java

private String readString(StringEntity entity) {
    try {/*from w w  w . j a  va 2  s.  c  o m*/
        return entity != null ? readString(entity.getContent()) : null;
    } catch (Exception exception) {
        throw new RuntimeException("Error reading String Entity", exception);
    }
}