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.esigate.DriverTest.java

public void testGzipErrorPage() throws Exception {
    Properties properties = new Properties();
    properties.put(Parameters.REMOTE_URL_BASE.getName(), "http://localhost");
    HttpResponse response = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1),
            HttpStatus.SC_INTERNAL_SERVER_ERROR, "Internal Server Error");
    response.addHeader("Content-type", "Text/html;Charset=UTF-8");
    response.addHeader("Content-encoding", "gzip");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GZIPOutputStream gzos = new GZIPOutputStream(baos);
    byte[] uncompressedBytes = "".getBytes("UTF-8");
    gzos.write(uncompressedBytes, 0, uncompressedBytes.length);
    gzos.close();//from  ww  w.ja va 2s  .c  om
    byte[] compressedBytes = baos.toByteArray();
    ByteArrayEntity httpEntity = new ByteArrayEntity(compressedBytes);
    httpEntity.setContentType("Text/html;Charset=UTF-8");
    httpEntity.setContentEncoding("gzip");
    response.setEntity(httpEntity);
    mockConnectionManager.setResponse(response);
    Driver driver = createMockDriver(properties, mockConnectionManager);
    CloseableHttpResponse driverResponse;
    try {
        driverResponse = driver.proxy("/", request.build());
        fail("We should get an HttpErrorPage");
    } catch (HttpErrorPage e) {
        driverResponse = e.getHttpResponse();
    }
    assertEquals("", HttpResponseUtils.toString(driverResponse));
}

From source file:me.code4fun.roboq.Request.java

private HttpEntity createBody(Object o) {
    Object o1 = o instanceof Body ? ((Body) o).content : o;
    String c1 = o instanceof Body ? ((Body) o).contentType : null;

    if (o1 instanceof byte[]) {
        ByteArrayEntity entity = new ByteArrayEntity((byte[]) o1) {
            @Override//from  ww w. j  ava 2 s .  com
            public void writeTo(OutputStream outstream) throws IOException {
                super.writeTo(decorateBodyOutput(outstream));
            }
        };
        entity.setContentType(c1 != null ? c1 : DEFAULT_BINARY_CONTENT_TYPE);
        return entity;
    } else if (o1 instanceof InputStream) {
        Long len = o instanceof Body ? ((Body) o).length : null;
        if (len == null)
            throw new RoboqException("Missing length in body for upload InputStream");

        InputStreamEntity entity = new InputStreamEntity((InputStream) o1, len) {
            @Override
            public void writeTo(OutputStream outstream) throws IOException {
                super.writeTo(decorateBodyOutput(outstream));
            }
        };
        entity.setContentType(c1 != null ? c1 : DEFAULT_BINARY_CONTENT_TYPE);
        return entity;
    } else if (o1 instanceof File) {
        File f = (File) o1;
        return new FileEntity(f, c1 != null ? c1 : getFileContentType(f)) {
            @Override
            public void writeTo(OutputStream outstream) throws IOException {
                super.writeTo(decorateBodyOutput(outstream));
            }
        };
    } else {
        String s = o2s(o1, "");
        String encoding = selectValue(fieldsEncoding, prepared != null ? prepared.fieldsEncoding : null,
                "UTF-8");
        try {
            StringEntity entity;
            entity = new StringEntity(s, encoding) {
                @Override
                public void writeTo(OutputStream outstream) throws IOException {
                    super.writeTo(decorateBodyOutput(outstream));
                }
            };
            entity.setContentType(c1 != null ? c1 : DEFAULT_TEXT_CONTENT_TYPE);
            return entity;
        } catch (UnsupportedEncodingException e) {
            throw new RoboqException("Illegal encoding for request body", e);
        }
    }
}

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

/** Send content
 *
 * @param content the content as bytes//from   w  w w.j  ava 2  s.  c  om
 * @param contentType its type
 * @throws HttpException
 */
public void setContent(final byte[] content, final String contentType) throws HttpException {
    if (!(method instanceof HttpEntityEnclosingRequestBase)) {
        throw new HttpException("Invalid operation for method " + method.getMethod());
    }

    final HttpEntityEnclosingRequestBase eem = (HttpEntityEnclosingRequestBase) method;

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

From source file:com.lehman.ic9.net.httpClient.java

/**
 * Sets request information for the type of POST request. This is determined 
 * by the post type provided./*from ww w .  j a v  a2s .  c o m*/
 * @param postTypeStr is a String with the postType.
 * @param Obj is a Javascript object to set for the request.
 * @param ContentType is a String with the content-type for the custom request.
 * @throws ic9exception Exception
 * @throws UnsupportedEncodingException Exception
 */
@SuppressWarnings("unchecked")
private void setPostInfo(String postTypeStr, Object Obj, String ContentType)
        throws ic9exception, UnsupportedEncodingException {
    postType pt = this.getPostType(postTypeStr);
    if (pt == postType.URL_ENCODED) {
        Map<String, Object> jobj = (Map<String, Object>) Obj;
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        for (String key : jobj.keySet()) {
            Object val = jobj.get(key);
            nvps.add(new BasicNameValuePair(key, val.toString()));
        }
        this.respEnt = new UrlEncodedFormEntity(nvps);
    } else if (pt == postType.MULTIPART) {
        MultipartEntityBuilder mpEntBuilder = MultipartEntityBuilder.create();
        Map<String, Object> jobj = (Map<String, Object>) Obj;
        for (String key : jobj.keySet()) {
            Map<String, Object> part = (Map<String, Object>) jobj.get(key);
            if (part.containsKey("name") && part.containsKey("data")) {
                String pkey = (String) part.get("name");
                if (part.get("data") instanceof byte[]) {
                    byte[] data = (byte[]) part.get("data");
                    mpEntBuilder.addPart(key, new ByteArrayBody(data, pkey));
                } else if (part.get("data") instanceof String) {
                    String data = (String) part.get("data");
                    mpEntBuilder.addPart(key,
                            new StringBody(data, org.apache.http.entity.ContentType.DEFAULT_TEXT));
                }
            } else
                throw new ic9exception(
                        "httpClient.setPotInfo(): Multipart from data expects and object of httpPart objects.");
        }
        this.respEnt = mpEntBuilder.build();
    } else {
        if (Obj instanceof String) {
            StringEntity se = new StringEntity((String) Obj);
            if (ContentType != null)
                se.setContentType(ContentType);
            else
                throw new ic9exception(
                        "httpClient.setPostInfo(): For custom postType, the third argument for content-type must be set.");
            this.respEnt = se;
        } else if (Obj instanceof Map) {
            Map<String, Object> tobj = (Map<String, Object>) Obj;

            if (tobj.containsKey("data") && tobj.get("data") instanceof byte[]) {
                if (ContentType != null) {
                    ByteArrayEntity bae = new ByteArrayEntity((byte[]) Obj);
                    bae.setContentType(ContentType);
                    this.respEnt = bae;
                } else
                    throw new ic9exception(
                            "httpClient.setPostInfo(): For custom postType, the third argument for content-type must be set.");
            } else
                throw new ic9exception(
                        "httpClient.setPostInfo(): Provided object is not of type Buffer or is missing 'data' attribute. (data should be byte[])");
        } else
            throw new ic9exception(
                    "httpClient.setPostInfo(): Second argument to POST call expecting String or Buffer object.");
    }
}

From source file:com.ettrema.httpclient.Host.java

public HttpResult doPut(Path path, byte[] data, String contentType) {
    String dest = buildEncodedUrl(path);
    LogUtils.trace(log, "doPut: ", dest);
    notifyStartRequest();/* w w w .j a v  a  2s .  co m*/
    HttpPut p = new HttpPut(dest);

    // Dont use transferService so we can use byte array
    try {
        ByteArrayEntity requestEntity = new ByteArrayEntity(data);
        requestEntity.setContentType(contentType);
        p.setEntity(requestEntity);
        HttpResult result = Utils.executeHttpWithResult(client, p, null);
        return result;
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    } finally {
        notifyFinishRequest();
    }
}

From source file:android.webkit.cts.CtsTestServer.java

/**
 * Generate a response to the given request.
 * @throws InterruptedException// w w w .  j av a 2  s. c  o m
 * @throws IOException
 */
private HttpResponse getResponse(HttpRequest request) throws Exception {
    RequestLine requestLine = request.getRequestLine();
    HttpResponse response = null;
    String uriString = requestLine.getUri();
    Log.i(TAG, requestLine.getMethod() + ": " + uriString);

    synchronized (this) {
        mQueries.add(uriString);
        mLastRequestMap.put(uriString, request);
        if (request instanceof HttpEntityEnclosingRequest) {
            mRequestEntities.add(((HttpEntityEnclosingRequest) request).getEntity());
        }
    }

    if (requestLine.getMethod().equals("POST")) {
        HttpResponse responseOnPost = onPost(request);
        if (responseOnPost != null) {
            return responseOnPost;
        }
    }

    URI uri = URI.create(uriString);
    String path = uri.getPath();
    String query = uri.getQuery();
    if (path.equals(FAVICON_PATH)) {
        path = FAVICON_ASSET_PATH;
    }
    if (path.startsWith(DELAY_PREFIX)) {
        String delayPath = path.substring(DELAY_PREFIX.length() + 1);
        String delay = delayPath.substring(0, delayPath.indexOf('/'));
        path = delayPath.substring(delay.length());
        try {
            Thread.sleep(Integer.valueOf(delay));
        } catch (InterruptedException ignored) {
            // ignore
        }
    }
    if (path.startsWith(AUTH_PREFIX)) {
        // authentication required
        Header[] auth = request.getHeaders("Authorization");
        if ((auth.length > 0 && auth[0].getValue().equals(AUTH_CREDENTIALS))
                // This is a hack to make sure that loads to this url's will always
                // ask for authentication. This is what the test expects.
                && !path.endsWith("embedded_image.html")) {
            // fall through and serve content
            path = path.substring(AUTH_PREFIX.length());
        } else {
            // request authorization
            response = createResponse(HttpStatus.SC_UNAUTHORIZED);
            response.addHeader("WWW-Authenticate", "Basic realm=\"" + AUTH_REALM + "\"");
        }
    }
    if (path.startsWith(BINARY_PREFIX)) {
        List<NameValuePair> args = URLEncodedUtils.parse(uri, "UTF-8");
        int length = 0;
        String mimeType = null;
        try {
            for (NameValuePair pair : args) {
                String name = pair.getName();
                if (name.equals("type")) {
                    mimeType = pair.getValue();
                } else if (name.equals("length")) {
                    length = Integer.parseInt(pair.getValue());
                }
            }
            if (length > 0 && mimeType != null) {
                ByteArrayEntity entity = new ByteArrayEntity(new byte[length]);
                entity.setContentType(mimeType);
                response = createResponse(HttpStatus.SC_OK);
                response.setEntity(entity);
                response.addHeader("Content-Disposition", "attachment; filename=test.bin");
                response.addHeader("Content-Type", mimeType);
                response.addHeader("Content-Length", "" + length);
            } else {
                // fall through, return 404 at the end
            }
        } catch (Exception e) {
            // fall through, return 404 at the end
            Log.w(TAG, e);
        }
    } else if (path.startsWith(ASSET_PREFIX)) {
        path = path.substring(ASSET_PREFIX.length());
        // request for an asset file
        try {
            InputStream in;
            if (path.startsWith(RAW_PREFIX)) {
                String resourceName = path.substring(RAW_PREFIX.length());
                int id = mResources.getIdentifier(resourceName, "raw", mContext.getPackageName());
                if (id == 0) {
                    Log.w(TAG, "Can't find raw resource " + resourceName);
                    throw new IOException();
                }
                in = mResources.openRawResource(id);
            } else {
                in = mAssets.open(path);
            }
            response = createResponse(HttpStatus.SC_OK);
            InputStreamEntity entity = new InputStreamEntity(in, in.available());
            String mimeType = mMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(path));
            if (mimeType == null) {
                mimeType = "text/html";
            }
            entity.setContentType(mimeType);
            response.setEntity(entity);
            if (query == null || !query.contains(NOLENGTH_POSTFIX)) {
                response.setHeader("Content-Length", "" + entity.getContentLength());
            }
        } catch (IOException e) {
            response = null;
            // fall through, return 404 at the end
        }
    } else if (path.startsWith(REDIRECT_PREFIX)) {
        response = createResponse(HttpStatus.SC_MOVED_TEMPORARILY);
        String location = getBaseUri() + path.substring(REDIRECT_PREFIX.length());
        Log.i(TAG, "Redirecting to: " + location);
        response.addHeader("Location", location);
    } else if (path.equals(QUERY_REDIRECT_PATH)) {
        String location = Uri.parse(uriString).getQueryParameter("dest");
        if (location != null) {
            Log.i(TAG, "Redirecting to: " + location);
            response = createResponse(HttpStatus.SC_MOVED_TEMPORARILY);
            response.addHeader("Location", location);
        }
    } else if (path.startsWith(COOKIE_PREFIX)) {
        /*
         * Return a page with a title containing a list of all incoming cookies,
         * separated by '|' characters. If a numeric 'count' value is passed in a cookie,
         * return a cookie with the value incremented by 1. Otherwise, return a cookie
         * setting 'count' to 0.
         */
        response = createResponse(HttpStatus.SC_OK);
        Header[] cookies = request.getHeaders("Cookie");
        Pattern p = Pattern.compile("count=(\\d+)");
        StringBuilder cookieString = new StringBuilder(100);
        cookieString.append(cookies.length);
        int count = 0;
        for (Header cookie : cookies) {
            cookieString.append("|");
            String value = cookie.getValue();
            cookieString.append(value);
            Matcher m = p.matcher(value);
            if (m.find()) {
                count = Integer.parseInt(m.group(1)) + 1;
            }
        }

        response.addHeader("Set-Cookie", "count=" + count + "; path=" + COOKIE_PREFIX);
        response.setEntity(createPage(cookieString.toString(), cookieString.toString()));
    } else if (path.startsWith(SET_COOKIE_PREFIX)) {
        response = createResponse(HttpStatus.SC_OK);
        Uri parsedUri = Uri.parse(uriString);
        String key = parsedUri.getQueryParameter("key");
        String value = parsedUri.getQueryParameter("value");
        String cookie = key + "=" + value;
        response.addHeader("Set-Cookie", cookie);
        response.setEntity(createPage(cookie, cookie));
    } else if (path.startsWith(LINKED_SCRIPT_PREFIX)) {
        response = createResponse(HttpStatus.SC_OK);
        String src = Uri.parse(uriString).getQueryParameter("url");
        String scriptTag = "<script src=\"" + src + "\"></script>";
        response.setEntity(createPage("LinkedScript", scriptTag));
    } else if (path.equals(USERAGENT_PATH)) {
        response = createResponse(HttpStatus.SC_OK);
        Header agentHeader = request.getFirstHeader("User-Agent");
        String agent = "";
        if (agentHeader != null) {
            agent = agentHeader.getValue();
        }
        response.setEntity(createPage(agent, agent));
    } else if (path.equals(TEST_DOWNLOAD_PATH)) {
        response = createTestDownloadResponse(Uri.parse(uriString));
    } else if (path.equals(SHUTDOWN_PREFIX)) {
        response = createResponse(HttpStatus.SC_OK);
        // We cannot close the socket here, because we need to respond.
        // Status must be set to OK, or else the test will fail due to
        // a RunTimeException.
    } else if (path.equals(APPCACHE_PATH)) {
        response = createResponse(HttpStatus.SC_OK);
        response.setEntity(createEntity("<!DOCTYPE HTML>" + "<html manifest=\"appcache.manifest\">" + "  <head>"
                + "    <title>Waiting</title>" + "    <script>"
                + "      function updateTitle(x) { document.title = x; }"
                + "      window.applicationCache.onnoupdate = "
                + "          function() { updateTitle(\"onnoupdate Callback\"); };"
                + "      window.applicationCache.oncached = "
                + "          function() { updateTitle(\"oncached Callback\"); };"
                + "      window.applicationCache.onupdateready = "
                + "          function() { updateTitle(\"onupdateready Callback\"); };"
                + "      window.applicationCache.onobsolete = "
                + "          function() { updateTitle(\"onobsolete Callback\"); };"
                + "      window.applicationCache.onerror = "
                + "          function() { updateTitle(\"onerror Callback\"); };" + "    </script>" + "  </head>"
                + "  <body onload=\"updateTitle('Loaded');\">AppCache test</body>" + "</html>"));
    } else if (path.equals(APPCACHE_MANIFEST_PATH)) {
        response = createResponse(HttpStatus.SC_OK);
        try {
            StringEntity entity = new StringEntity("CACHE MANIFEST");
            // This entity property is not used when constructing the response, (See
            // AbstractMessageWriter.write(), which is called by
            // AbstractHttpServerConnection.sendResponseHeader()) so we have to set this header
            // manually.
            // TODO: Should we do this for all responses from this server?
            entity.setContentType("text/cache-manifest");
            response.setEntity(entity);
            response.setHeader("Content-Type", "text/cache-manifest");
        } catch (UnsupportedEncodingException e) {
            Log.w(TAG, "Unexpected UnsupportedEncodingException");
        }
    }
    if (response == null) {
        response = createResponse(HttpStatus.SC_NOT_FOUND);
    }
    StatusLine sl = response.getStatusLine();
    Log.i(TAG, sl.getStatusCode() + "(" + sl.getReasonPhrase() + ")");
    setDateHeaders(response);
    return response;
}

From source file:ch.iterate.openstack.swift.Client.java

/**
 * Create a manifest on the server, including metadata
 *
 * @param container   The name of the container
 * @param contentType The MIME type of the file
 * @param name        The name of the file on the server
 * @param manifest    Set manifest content here
 * @param metadata    A map with the metadata as key names and values as the metadata values
 * @return True if response code is 201//from  w ww.  ja  v  a  2 s  . c o m
 * @throws GenericException Unexpected response
 */
public boolean createManifestObject(Region region, String container, String contentType, String name,
        String manifest, Map<String, String> metadata) throws IOException {
    byte[] arr = new byte[0];
    HttpPut method = new HttpPut(region.getStorageUrl(container, name));
    method.setHeader(Constants.MANIFEST_HEADER, manifest);
    ByteArrayEntity entity = new ByteArrayEntity(arr);
    entity.setContentType(contentType);
    method.setEntity(entity);
    for (Map.Entry<String, String> key : this.renameObjectMetadata(metadata).entrySet()) {
        method.setHeader(key.getKey(), key.getValue());
    }
    Response response = this.execute(method, new DefaultResponseHandler());
    if (response.getStatusCode() == HttpStatus.SC_CREATED) {
        return true;
    } else {
        throw new GenericException(response);
    }
}

From source file:com.bigdata.rdf.sail.webapp.client.RemoteRepository.java

/**
 * Post a GraphML file to the blueprints layer of the remote bigdata instance.
 *///ww w.  j a  v  a2  s  .com
public long postGraphML(final String path) throws Exception {

    // TODO Allow client to specify UUID for postGraphML. See #1254.
    final UUID uuid = UUID.randomUUID();

    final ConnectOptions opts = mgr.newConnectOptions(sparqlEndpointURL, uuid, tx);

    opts.addRequestParam("blueprints");

    JettyResponseListener response = null;
    try {

        final File file = new File(path);

        if (!file.exists()) {
            throw new RuntimeException("cannot locate file: " + file.getAbsolutePath());
        }

        final byte[] data = IOUtil.readBytes(file);

        final ByteArrayEntity entity = new ByteArrayEntity(data);

        entity.setContentType(ConnectOptions.MIME_GRAPH_ML);

        opts.entity = entity;

        opts.setAcceptHeader(ConnectOptions.MIME_APPLICATION_XML);

        checkResponseCode(response = doConnect(opts));

        final MutationResult result = mutationResults(response);

        return result.mutationCount;

    } finally {

        if (response != null)
            response.abort();

    }

}