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

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

Introduction

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

Prototype

public void setContentType(Header header) 

Source Link

Usage

From source file:org.thoughtcrime.securesms.mms.MmsSendHelper.java

private static byte[] makePost(MmsConnectionParameters parameters, byte[] mms)
        throws ClientProtocolException, IOException {
    Log.w("MmsSender", "Sending MMS1 of length: " + mms.length);
    try {//from  w w w.j a va2 s.  c  o  m
        HttpClient client = constructHttpClient(parameters);
        URI hostUrl = new URI(parameters.getMmsc());
        HttpHost target = new HttpHost(hostUrl.getHost(), hostUrl.getPort(), HttpHost.DEFAULT_SCHEME_NAME);
        HttpPost request = new HttpPost(parameters.getMmsc());
        ByteArrayEntity entity = new ByteArrayEntity(mms);

        entity.setContentType("application/vnd.wap.mms-message");

        request.setEntity(entity);
        request.setParams(client.getParams());
        request.addHeader("Accept", "*/*, application/vnd.wap.mms-message, application/vnd.wap.sic");

        HttpResponse response = client.execute(target, request);
        StatusLine status = response.getStatusLine();

        if (status.getStatusCode() != 200)
            throw new IOException("Non-successful HTTP response: " + status.getReasonPhrase());

        return parseResponse(response.getEntity());
    } catch (URISyntaxException use) {
        Log.w("MmsDownlader", use);
        throw new IOException("Bad URI syntax");
    }
}

From source file:org.ow2.bonita.facade.rest.apachehttpclient.ApacheHttpClientUtil.java

public static HttpResponse executeHttpConnection(String uri, byte[] content, String optionsHeader,
        String username, String password)
        throws URISyntaxException, IOException, IOException, ClassNotFoundException {
    String serverAddress = HttpRESTUtil.getRESTServerAddress();
    HttpPost post = new HttpPost(serverAddress + uri);

    ByteArrayEntity entity = new ByteArrayEntity(content);
    entity.setContentType("application/octet-stream");
    post.setHeader("options", optionsHeader);
    post.setEntity(entity);/*from www.j  a v a  2  s .  c om*/

    HttpClient client = ApacheHttpClientUtil.getHttpClient(serverAddress, username, password);
    HttpResponse httpresponse = client.execute(post);
    return httpresponse;
}

From source file:com.facebook.stetho.dumpapp.RawDumpappHandler.java

private static HttpEntity createResponseEntity(byte[] data) {
    ByteArrayEntity entity = new ByteArrayEntity(data);
    if (isProbablyBinaryData(data)) {
        entity.setContentType(HTTP.OCTET_STREAM_TYPE);
    } else {//from  w  w w. jav a  2 s .  c om
        entity.setContentType(HTTP.PLAIN_TEXT_TYPE);
    }
    return entity;
}

From source file:org.fdroid.enigtext.mms.MmsSendHelper.java

private static byte[] makePost(Context context, MmsConnectionParameters parameters, byte[] mms)
        throws ClientProtocolException, IOException {
    AndroidHttpClient client = null;/*from  w w w.j  a  v  a2s.c o m*/

    try {
        Log.w("MmsSender", "Sending MMS1 of length: " + (mms != null ? mms.length : "null"));
        client = constructHttpClient(context, parameters);
        URI targetUrl = new URI(parameters.getMmsc());

        if (Util.isEmpty(targetUrl.getHost()))
            throw new IOException("Invalid target host: " + targetUrl.getHost() + " , " + targetUrl);

        HttpHost target = new HttpHost(targetUrl.getHost(), targetUrl.getPort(), HttpHost.DEFAULT_SCHEME_NAME);
        HttpPost request = new HttpPost(parameters.getMmsc());
        ByteArrayEntity entity = new ByteArrayEntity(mms);

        entity.setContentType("application/vnd.wap.mms-message");

        request.setEntity(entity);
        request.setParams(client.getParams());
        request.addHeader("Accept", "*/*, application/vnd.wap.mms-message, application/vnd.wap.sic");
        request.addHeader("x-wap-profile", "http://www.google.com/oha/rdf/ua-profile-kila.xml");
        HttpResponse response = client.execute(target, request);
        StatusLine status = response.getStatusLine();

        if (status.getStatusCode() != 200)
            throw new IOException("Non-successful HTTP response: " + status.getReasonPhrase());

        return parseResponse(response.getEntity());
    } catch (URISyntaxException use) {
        Log.w("MmsSendHelper", use);
        throw new IOException("Couldn't parse URI.");
    } finally {
        if (client != null)
            client.close();
    }
}

From source file:org.bedework.util.http.HttpUtil.java

/** Send content
 *
 * @param content the content as bytes/*from   w w w  .ja v  a2 s .  c  om*/
 * @param contentType its type
 * @throws HttpException if not entity enclosing request
 */
public static void setContent(final HttpRequestBase req, final byte[] content, final String contentType)
        throws HttpException {
    if (content == null) {
        return;
    }

    if (!(req instanceof HttpEntityEnclosingRequestBase)) {
        throw new HttpException("Invalid operation for method " + req.getMethod());
    }

    final HttpEntityEnclosingRequestBase eem = (HttpEntityEnclosingRequestBase) req;

    final ByteArrayEntity entity = new ByteArrayEntity(content);
    entity.setContentType(contentType);
    eem.setEntity(entity);
}

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./* w w  w.  ja va 2  s.c  o  m*/
 * @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 (>=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();
        }
    }
}

From source file:com.nominanuda.hyperapi.ByteArrayEntityEncoder.java

@Override
protected HttpEntity encodeInternal(AnnotatedType p, byte[] barr) {
    String ct = Check.ifNullOrBlank(p.mediaType(), defaultContentType);
    ByteArrayEntity entity = new ByteArrayEntity(barr);
    entity.setContentType(ct);
    return entity;
}

From source file:com.nominanuda.hyperapi.JsonAnyValueEntityEncoder.java

@Override
protected HttpEntity encodeInternal(AnnotatedType p, Object value) {
    byte[] payload = STRUCT.toJsonString(value).getBytes(Strings.UTF8);
    ByteArrayEntity e = new ByteArrayEntity(payload);
    e.setContentType(HttpProtocol.CT_APPLICATION_JSON_CS_UTF8);
    return e;/* ww w. j a va 2  s  .com*/
}

From source file:com.nominanuda.hyperapi.DataStructJsonEntityEncoder.java

@Override
protected HttpEntity encodeInternal(AnnotatedType p, DataStruct value) {
    byte[] payload = STRUCT.toJsonString(value).getBytes(Strings.UTF8);
    ByteArrayEntity e = new ByteArrayEntity(payload);
    e.setContentType(HttpProtocol.CT_APPLICATION_JSON_CS_UTF8);
    return e;//from   ww w .j ava2 s . c o m
}

From source file:com.nominanuda.hyperapi.InputStreamEntityEncoder.java

@Override
protected HttpEntity encodeInternal(AnnotatedType p, InputStream value) {
    try {/*from w w w  .j a v  a  2s.c o  m*/
        byte[] barr = IO.read(value, true);
        String ct = Check.ifNullOrBlank(p.mediaType(), defaultContentType);
        ByteArrayEntity entity = new ByteArrayEntity(barr);
        entity.setContentType(ct);
        return entity;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}