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

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

Introduction

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

Prototype

public InputStream getContent() 

Source Link

Usage

From source file:com.deployd.Deployd.java

public static JSONObject delete(String uri) throws ClientProtocolException, IOException, JSONException {

    HttpDelete post = new HttpDelete(endpoint + uri);
    HttpClient client = new DefaultHttpClient();
    HttpResponse response = client.execute(post);
    ByteArrayEntity e = (ByteArrayEntity) response.getEntity();
    InputStream is = e.getContent();
    String data = new Scanner(is).next();
    JSONObject result = new JSONObject(data);
    return result;
}

From source file:com.deployd.Deployd.java

public static JSONObject get(String uri) throws ClientProtocolException, IOException, JSONException {

    HttpGet post = new HttpGet(endpoint + uri);
    HttpClient client = new DefaultHttpClient();
    HttpResponse response = client.execute(post);
    ByteArrayEntity e = (ByteArrayEntity) response.getEntity();
    InputStream is = e.getContent();
    String data = new Scanner(is).next();
    JSONObject result = new JSONObject(data);
    return result;
}

From source file:com.deployd.Deployd.java

public static JSONObject put(JSONObject input, String uri)
        throws ClientProtocolException, IOException, JSONException {

    HttpPut post = new HttpPut(endpoint + uri);
    HttpClient client = new DefaultHttpClient();
    post.setEntity(new ByteArrayEntity(input.toString().getBytes("UTF8")));
    HttpResponse response = client.execute(post);
    ByteArrayEntity e = (ByteArrayEntity) response.getEntity();
    InputStream is = e.getContent();
    String data = new Scanner(is).next();
    JSONObject result = new JSONObject(data);
    return result;
}

From source file:com.deployd.Deployd.java

public static JSONObject post(JSONObject input, String uri)
        throws ClientProtocolException, IOException, JSONException {

    HttpPost post = new HttpPost(endpoint + uri);
    HttpClient client = new DefaultHttpClient();
    post.setEntity(new ByteArrayEntity(input.toString().getBytes("UTF8")));
    HttpResponse response = client.execute(post);
    ByteArrayEntity e = (ByteArrayEntity) response.getEntity();
    InputStream is = e.getContent();
    String data = new Scanner(is).next();
    JSONObject result = new JSONObject(data);
    return result;
}

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

protected String putFile(String uri, String name, File data) throws IOException {
    // bei SharePoint 2010 funktioniert FileEntity nicht, deshalb zuerst in Memory lesen
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    if (data != null) {
        byte buf[] = new byte[128 * 32768];
        InputStream inp = new FileInputStream(data);
        for (int length; (length = inp.read(buf, 0, buf.length)) > 0;)
            out.write(buf, 0, length);//from w  w w .  j a  v a 2  s . c o  m
        out.close();
        inp.close();
    }

    HttpPut request = new HttpPut(remote + "/" + uri + "/" + name);
    request.addHeader("Accept", "application/json;odata=verbose;charset=utf-8");
    request.addHeader("Content-Type", "application/msword");

    if (data != null) {
        ByteArrayEntity entity = new ByteArrayEntity(out.toByteArray());
        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:ch.admin.hermes.etl.load.SharePoint2010RESTClient.java

protected String putFile(String uri, String name, URL url) throws IOException, URISyntaxException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    if (url != null) {
        HttpGet req = new HttpGet(url.toURI());
        req.addHeader("Accept", "application/json;odata=verbose;charset=utf-8");
        req.addHeader("Content-Type", "application/msword");

        HttpResponse resp = client.execute(req);
        checkError(resp, url.toString());

        byte buf[] = new byte[128 * 32768];
        InputStream inp = resp.getEntity().getContent();
        for (int length; (length = inp.read(buf, 0, buf.length)) > 0;)
            out.write(buf, 0, length);//ww  w  .j a  va2s .  co m
        out.close();

        EntityUtils.consume(resp.getEntity());
    }

    HttpPut request = new HttpPut(remote + "/" + uri + "/" + name);
    request.addHeader("Accept", "application/json;odata=verbose;charset=utf-8");
    request.addHeader("Content-Type", "application/msword");

    if (url != null) {
        ByteArrayEntity entity = new ByteArrayEntity(out.toByteArray());
        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:ch.admin.hermes.etl.load.SharePointRESTClient.java

public String postFile(String uri, URL url) throws IOException, URISyntaxException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    if (url != null) {
        HttpGet req = new HttpGet(url.toURI());
        req.addHeader("Accept", "application/json;odata=verbose;charset=utf-8");
        req.addHeader("Content-Type", "application/msword");

        HttpResponse resp = client.execute(req);
        checkError(resp, url.toString());

        byte buf[] = new byte[128 * 32768];
        InputStream inp = resp.getEntity().getContent();
        for (int length; (length = inp.read(buf, 0, buf.length)) > 0;)
            out.write(buf, 0, length);//from w w w  . j av a  2  s  .c  om
        out.close();

        EntityUtils.consume(resp.getEntity());
    }

    HttpPost request = new HttpPost(remote + uri);
    request.addHeader("Accept", "application/json;odata=verbose;charset=utf-8");
    request.addHeader("Content-Type", "application/msword");

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

    if (url != null) {
        ByteArrayEntity entity = new ByteArrayEntity(out.toByteArray());
        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.microsoft.services.orc.http.impl.AndroidNetworkRunnable.java

@Override
public void run() {
    AndroidHttpClient client = null;/*  ww  w . j a va  2  s.com*/
    try {

        String userAgent = mRequest.getHeaders().get(Constants.USER_AGENT_HEADER);

        if (userAgent == null) {
            userAgent = "";
        }

        client = AndroidHttpClient.newInstance(userAgent);

        BasicHttpEntityEnclosingRequest realRequest = new BasicHttpEntityEnclosingRequest(
                mRequest.getVerb().toString(), mRequest.getUrl().toString());
        EntityEnclosingRequestWrapper wrapper = new EntityEnclosingRequestWrapper(realRequest);

        Map<String, String> headers = mRequest.getHeaders();
        for (String key : headers.keySet()) {
            wrapper.addHeader(key, headers.get(key));
        }

        if (mRequest.getContent() != null) {
            ByteArrayEntity entity = new ByteArrayEntity(mRequest.getContent());
            wrapper.setEntity(entity);
        } else if (mRequest.getStreamedContent() != null) {
            InputStream stream = mRequest.getStreamedContent();
            InputStreamEntity entity = new InputStreamEntity(stream, mRequest.getStreamedContentSize());
            wrapper.setEntity(entity);
        }

        HttpResponse realResponse = client.execute(wrapper);
        int status = realResponse.getStatusLine().getStatusCode();

        Map<String, List<String>> responseHeaders = new HashMap<String, List<String>>();
        for (Header header : realResponse.getAllHeaders()) {
            List<String> headerValues = new ArrayList<String>();
            for (HeaderElement element : header.getElements()) {
                headerValues.add(element.getValue());
            }
            responseHeaders.put(header.getName(), headerValues);
        }

        HttpEntity entity = realResponse.getEntity();
        InputStream stream = null;

        if (entity != null) {
            stream = entity.getContent();
        }

        if (stream != null) {
            final AndroidHttpClient finalClient = client;
            Closeable closeable = new Closeable() {
                @Override
                public void close() throws IOException {
                    finalClient.close();
                }
            };

            Response response = new ResponseImpl(stream, status, responseHeaders, closeable);

            mFuture.set(response);
        } else {
            client.close();
            mFuture.set(new EmptyResponse(status, responseHeaders));
        }

    } catch (Throwable t) {
        if (client != null) {
            client.close();
        }

        mFuture.setException(t);
    }
}

From source file:com.android.mms.service.HttpUtils.java

/**
 * A helper method to send or retrieve data through HTTP protocol.
 *
 * @param url The URL used in a GET request. Null when the method is
 *         HTTP_POST_METHOD./*from w  ww  .  j  a  va 2  s.  com*/
 * @param pdu The data to be POST. Null when the method is HTTP_GET_METHOD.
 * @param method HTTP_POST_METHOD or HTTP_GET_METHOD.
 * @param isProxySet If proxy is set
 * @param proxyHost The host of the proxy
 * @param proxyPort The port of the proxy
 * @param resolver The custom name resolver to use
 * @param useIpv6 If we should use IPv6 address when the HTTP client resolves the host name
 * @param mmsConfig The MmsConfig to use
 * @return A byte array which contains the response data.
 *         If an HTTP error code is returned, an IOException will be thrown.
 * @throws com.android.mms.service.exception.MmsHttpException if HTTP request gets error response (&gt;=400)
 */
public static byte[] httpConnection(Context context, String url, byte[] pdu, int method, boolean isProxySet,
        String proxyHost, int proxyPort, NameResolver resolver, boolean useIpv6, MmsConfig.Overridden mmsConfig)
        throws MmsHttpException {
    final String methodString = getMethodString(method);
    Log.v(TAG,
            "HttpUtils: request param list\n" + "url=" + url + "\n" + "method=" + methodString + "\n"
                    + "isProxySet=" + isProxySet + "\n" + "proxyHost=" + proxyHost + "\n" + "proxyPort="
                    + proxyPort + "\n" + "size=" + (pdu != null ? pdu.length : 0));

    NetworkAwareHttpClient client = null;
    try {
        // Make sure to use a proxy which supports CONNECT.
        URI hostUrl = new URI(url);
        HttpHost target = new HttpHost(hostUrl.getHost(), hostUrl.getPort(), HttpHost.DEFAULT_SCHEME_NAME);
        client = createHttpClient(context, resolver, useIpv6, mmsConfig);
        HttpRequest req = null;

        switch (method) {
        case HTTP_POST_METHOD:
            ByteArrayEntity entity = new ByteArrayEntity(pdu);
            // Set request content type.
            entity.setContentType("application/vnd.wap.mms-message");
            HttpPost post = new HttpPost(url);
            post.setEntity(entity);
            req = post;
            break;
        case HTTP_GET_METHOD:
            req = new HttpGet(url);
            break;
        }

        // Set route parameters for the request.
        HttpParams params = client.getParams();
        if (isProxySet) {
            ConnRouteParams.setDefaultProxy(params, new HttpHost(proxyHost, proxyPort));
        }
        req.setParams(params);

        // Set necessary HTTP headers for MMS transmission.
        req.addHeader(HDR_KEY_ACCEPT, HDR_VALUE_ACCEPT);

        // UA Profile URL header
        String xWapProfileTagName = mmsConfig.getUaProfTagName();
        String xWapProfileUrl = mmsConfig.getUaProfUrl();
        if (xWapProfileUrl != null) {
            Log.v(TAG, "HttpUtils: xWapProfUrl=" + xWapProfileUrl);
            req.addHeader(xWapProfileTagName, xWapProfileUrl);
        }

        // Extra http parameters. Split by '|' to get a list of value pairs.
        // Separate each pair by the first occurrence of ':' to obtain a name and
        // value. Replace the occurrence of the string returned by
        // MmsConfig.getHttpParamsLine1Key() with the users telephone number inside
        // the value. And replace the occurrence of the string returned by
        // MmsConfig.getHttpParamsNaiKey() with the users NAI(Network Access Identifier)
        // inside the value.
        String extraHttpParams = mmsConfig.getHttpParams();

        if (!TextUtils.isEmpty(extraHttpParams)) {
            // Parse the parameter list
            String paramList[] = extraHttpParams.split("\\|");
            for (String paramPair : paramList) {
                String splitPair[] = paramPair.split(":", 2);
                if (splitPair.length == 2) {
                    final String name = splitPair[0].trim();
                    final String value = resolveMacro(context, splitPair[1].trim(), mmsConfig);
                    if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(value)) {
                        req.addHeader(name, value);
                    }
                }
            }
        }
        req.addHeader(HDR_KEY_ACCEPT_LANGUAGE, getCurrentAcceptLanguage(Locale.getDefault()));

        final HttpResponse response = client.execute(target, req);
        final StatusLine status = response.getStatusLine();
        final HttpEntity entity = response.getEntity();
        Log.d(TAG,
                "HttpUtils: status=" + status + " size=" + (entity != null ? entity.getContentLength() : -1));
        for (Header header : req.getAllHeaders()) {
            if (header != null) {
                Log.v(TAG, "HttpUtils: header " + header.getName() + "=" + header.getValue());
            }
        }
        byte[] body = null;
        if (entity != null) {
            try {
                if (entity.getContentLength() > 0) {
                    body = new byte[(int) entity.getContentLength()];
                    DataInputStream dis = new DataInputStream(entity.getContent());
                    try {
                        dis.readFully(body);
                    } finally {
                        try {
                            dis.close();
                        } catch (IOException e) {
                            Log.e(TAG, "HttpUtils: Error closing input stream: " + e.getMessage());
                        }
                    }
                }
                if (entity.isChunked()) {
                    Log.d(TAG, "HttpUtils: transfer encoding is chunked");
                    int bytesTobeRead = mmsConfig.getMaxMessageSize();
                    byte[] tempBody = new byte[bytesTobeRead];
                    DataInputStream dis = new DataInputStream(entity.getContent());
                    try {
                        int bytesRead = 0;
                        int offset = 0;
                        boolean readError = false;
                        do {
                            try {
                                bytesRead = dis.read(tempBody, offset, bytesTobeRead);
                            } catch (IOException e) {
                                readError = true;
                                Log.e(TAG, "HttpUtils: error reading input stream", e);
                                break;
                            }
                            if (bytesRead > 0) {
                                bytesTobeRead -= bytesRead;
                                offset += bytesRead;
                            }
                        } while (bytesRead >= 0 && bytesTobeRead > 0);
                        if (bytesRead == -1 && offset > 0 && !readError) {
                            // offset is same as total number of bytes read
                            // bytesRead will be -1 if the data was read till the eof
                            body = new byte[offset];
                            System.arraycopy(tempBody, 0, body, 0, offset);
                            Log.d(TAG, "HttpUtils: Chunked response length " + offset);
                        } else {
                            Log.e(TAG, "HttpUtils: Response entity too large or empty");
                        }
                    } finally {
                        try {
                            dis.close();
                        } catch (IOException e) {
                            Log.e(TAG, "HttpUtils: Error closing input stream", e);
                        }
                    }
                }
            } finally {
                if (entity != null) {
                    entity.consumeContent();
                }
            }
        }
        if (status.getStatusCode() != 200) { // HTTP 200 is success.
            StringBuilder sb = new StringBuilder();
            if (body != null) {
                sb.append("response: text=").append(new String(body)).append('\n');
            }
            for (Header header : req.getAllHeaders()) {
                if (header != null) {
                    sb.append("req header: ").append(header.getName()).append('=').append(header.getValue())
                            .append('\n');
                }
            }
            for (Header header : response.getAllHeaders()) {
                if (header != null) {
                    sb.append("resp header: ").append(header.getName()).append('=').append(header.getValue())
                            .append('\n');
                }
            }
            Log.e(TAG,
                    "HttpUtils: error response -- \n" + "mStatusCode=" + status.getStatusCode() + "\n"
                            + "reason=" + status.getReasonPhrase() + "\n" + "url=" + url + "\n" + "method="
                            + methodString + "\n" + "isProxySet=" + isProxySet + "\n" + "proxyHost=" + proxyHost
                            + "\n" + "proxyPort=" + proxyPort + (sb != null ? "\n" + sb.toString() : ""));
            throw new MmsHttpException(status.getReasonPhrase());
        }
        return body;
    } catch (IOException e) {
        Log.e(TAG, "HttpUtils: IO failure", e);
        throw new MmsHttpException(e);
    } catch (URISyntaxException e) {
        Log.e(TAG, "HttpUtils: invalid url " + url);
        throw new MmsHttpException("Invalid url " + url);
    } finally {
        if (client != null) {
            client.close();
        }
    }
}