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

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

Introduction

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

Prototype

public ByteArrayEntity(byte[] bArr) 

Source Link

Usage

From source file:com.apigee.sdk.apm.http.impl.client.cache.BasicHttpCache.java

HttpResponse generateIncompleteResponseError(HttpResponse response, Resource resource) {
    int contentLength = Integer.parseInt(response.getFirstHeader("Content-Length").getValue());
    HttpResponse error = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_BAD_GATEWAY, "Bad Gateway");
    error.setHeader("Content-Type", "text/plain;charset=UTF-8");
    String msg = String.format(
            "Received incomplete response " + "with Content-Length %d but actual body length %d", contentLength,
            resource.length());/*from  w  w  w .  jav  a2s  .  c o  m*/
    byte[] msgBytes = msg.getBytes();
    error.setHeader("Content-Length", Integer.toString(msgBytes.length));
    error.setEntity(new ByteArrayEntity(msgBytes));
    return error;
}

From source file:org.apache.edgent.connectors.http.HttpStreams.java

/**
 * Make an HTTP POST request with JsonObject. <br>
 * //from  ww  w. j  av  a 2s .com
 * Method specifically works with JsonObjects. For each JsonObject in the stream, 
 * HTTP POST request is executed on provided uri. Request body is filled using
 * HttpEntity provided by body function. As a result, Response is added to
 * the response TStream.<br>
 * 
 * Sample usage:<br>
 * 
 * <pre>
 * {@code
 *     DirectProvider ep = new DirectProvider();
 *     Topology topology = ep.newTopology();
 *     final String url = "http://httpbin.org/post";
 * 
 *     JsonObject body = new JsonObject();
 *     body.addProperty("foo", "abc");
 *     body.addProperty("bar", 42);
 * 
 *     TStream<JsonObject> stream = topology.collection(Arrays.asList(body));
 *     TStream<JsonObject> rc = HttpStreams.postJson(stream,
 *             HttpClients::noAuthentication, t -> url, t -> t);
 * }
 * </pre>
 * 
 * <br>
 * See HttpTest for example. <br>
 * 
 * @param stream - JsonObject TStream.
 * @param clientCreator - CloseableHttpClient supplier preferably created using {@link HttpClients}
 * @param uri - URI function which returns URI string
 * @param body - Function that returns JsonObject which will be set as a body for the request.
 * @return TStream of JsonObject which contains responses of POST requests
 * 
 * @see HttpStreams#requestsWithBody(TStream, Supplier, Function, Function, Function, BiFunction)
 */
public static TStream<JsonObject> postJson(TStream<JsonObject> stream,
        Supplier<CloseableHttpClient> clientCreator, Function<JsonObject, String> uri,
        UnaryOperator<JsonObject> body) {

    return HttpStreams.<JsonObject, JsonObject>requestsWithBody(stream, clientCreator,
            t -> HttpPost.METHOD_NAME, uri, t -> new ByteArrayEntity(body.apply(t).toString().getBytes()),
            HttpResponders.json());
}

From source file:org.perfrepo.client.PerfRepoClient.java

private void setPostEntity(HttpPost req, Object obj) {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    JAXB.marshal(obj, bos);//  w ww  .  ja  v  a  2  s  . co  m
    req.setEntity(new ByteArrayEntity(bos.toByteArray()));
}

From source file:processing.core.PRequest.java

/** @hidden */
public void run() {
    try {// ww w .ja v a 2  s.  com
        if (client == null) {
            //instance the client
            client = new DefaultHttpClient();
            HttpParams params = client.getParams();
            //open connection to server
            //request type depends on content type var
            if (contentType != null) {
                request = new HttpPost(url);
                //which content types are posted?               
                params.setParameter("Content-Type", contentType);
                //create a byte array entity and add to post
                if (bytes != null) {
                    ByteArrayEntity entity = new ByteArrayEntity(bytes);
                    ((HttpPost) request).setEntity(entity);
                    //we can release the request bytes and reuse the
                    // reference
                    bytes = null;
                }
            } else {
                request = new HttpGet(url);
            }
            if (authorization != null) {
                params.setParameter("Authorization", authorization);
            }
            params.setParameter("Connection", "close");
            request.setParams(params);
            //
            client.execute(request, new StateResponseHandler<Integer>());
            // done, notify midlet
            boolean notify = false;
            synchronized (this) {
                if (state == STATE_OPENED) {
                    state = STATE_CONNECTED;
                    notify = true;
                }
            }
            if (notify) {
                midlet.enqueueLibraryEvent(this, EVENT_CONNECTED, null);
            }
        } else {
            synchronized (this) {
                if (state == STATE_CONNECTED) {
                    state = STATE_FETCHING;
                } else {
                    throw new Exception("Not connected.");
                }
            }
            // read the response
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int bytesRead = is.read(buffer);
            while (bytesRead >= 0) {
                baos.write(buffer, 0, bytesRead);
                bytesRead = is.read(buffer);
            }
            buffer = null;
            buffer = baos.toByteArray();
            // done, notify midlet
            boolean notify = false;
            synchronized (this) {
                if (state == STATE_FETCHING) {
                    state = STATE_DONE;
                    notify = true;
                }
            }
            if (notify) {
                midlet.enqueueLibraryEvent(this, EVENT_DONE, buffer);
            }
        }
    } catch (Exception e) {
        boolean notify = false;
        synchronized (this) {
            if ((state == STATE_CONNECTED) || (state == STATE_FETCHING)) {
                notify = true;
            }
        }
        close();
        if (notify) {
            synchronized (this) {
                state = STATE_ERROR;
            }
            midlet.enqueueLibraryEvent(this, EVENT_ERROR, e.getMessage());
        }
    } finally {

    }
}

From source file:com.seleritycorp.common.base.http.client.FileHttpClient.java

@Override
protected CloseableHttpResponse doExecute(HttpHost target, HttpRequest request, HttpContext context)
        throws IOException, ClientProtocolException {
    final StatusLine statusLine;
    final FileHttpClientResponse response;
    byte[] content = null;

    String uri = request.getRequestLine().getUri();
    if (uri.startsWith("file://")) {
        File file = new File(URI.create(uri));
        uri = file.getAbsolutePath();/*from  www .  j av  a  2s  .c o m*/
    }
    Path path = Paths.get(uri);

    if (request instanceof HttpGet) {
        if (Files.exists(path)) {
            if (Files.isReadable(path)) {
                if (!Files.isDirectory(path)) {
                    content = Files.readAllBytes(path);
                    statusLine = createStatusLine(HttpStatus.SC_OK, "OK");
                } else {
                    // Trying to GET a directory
                    statusLine = createStatusLine(HttpStatus.SC_BAD_REQUEST, "Bad Request");
                }
            } else {
                // User does not have sufficient privilege to access the file
                statusLine = createStatusLine(HttpStatus.SC_FORBIDDEN, "Forbidden");
            }
        } else {
            // File does not exist.
            statusLine = createStatusLine(HttpStatus.SC_NOT_FOUND, "Not Found");
        }
    } else {
        // Request is not a HttpGet request. We currently only support GET, so we flag that the
        // client sent an illegal request.
        statusLine = createStatusLine(HttpStatus.SC_BAD_REQUEST, "Bad Request");
    }

    response = new FileHttpClientResponse(statusLine);
    if (content != null) {
        response.setEntity(new ByteArrayEntity(content));
    }

    return response;
}

From source file:com.example.aliyundemo.ocr.util.HttpUtil.java

/**
 * HTTP POST /*from  www .  jav  a2  s.c o  m*/
 *
 * @param url                  http://host+path+query
 * @param headers              Http
 * @param bytes                
 * @param appKey               APP KEY
 * @param appSecret            APP
 * @param timeout              
 * @param signHeaderPrefixList ???Header?
 * @return 
 * @throws Exception
 */
public static HttpResponse httpPost(String url, Map<String, String> headers, byte[] bytes, String appKey,
        String appSecret, int timeout, List<String> signHeaderPrefixList) throws Exception {
    headers = initialBasicHeader(headers, appKey, appSecret, HttpMethod.POST, url, null, signHeaderPrefixList);
    HttpClient httpClient = new DefaultHttpClient();
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, getTimeout(timeout));

    HttpPost post = new HttpPost(url);
    for (Map.Entry<String, String> e : headers.entrySet()) {
        post.addHeader(e.getKey(), MessageDigestUtil.utf8ToIso88591(e.getValue()));
    }

    if (bytes != null) {
        post.setEntity(new ByteArrayEntity(bytes));

    }

    return httpClient.execute(post);
}

From source file:org.modeshape.web.jcr.rest.client.http.HttpClientConnection.java

/**
 * @param bytes the bytes being posted to the HTTP connection (never <code>null</code>)
 * @throws Exception if there is a problem writing to the connection
 *///from   w  w  w  .ja v a  2 s.co  m
public void write(byte[] bytes) throws Exception {
    assert bytes != null;

    ByteArrayEntity entity = new ByteArrayEntity(bytes);
    if (contentType == null) {
        entity.setContentType(MediaType.APPLICATION_JSON);
    }

    if (this.request instanceof HttpEntityEnclosingRequestBase) {
        ((HttpEntityEnclosingRequestBase) this.request).setEntity(entity);
    }
}

From source file:eu.fusepool.p3.proxy.ProxyHandler.java

@Override
public void handle(String target, Request baseRequest, final HttpServletRequest inRequest,
        final HttpServletResponse outResponse) throws IOException, ServletException {
    final String targetUriString = targetBaseUri + inRequest.getRequestURI();
    final String requestUri = getFullRequestUrl(inRequest);
    //System.out.println(targetUriString);
    final URI targetUri;
    try {//from  w  w w.  j  a  va  2s.  com
        targetUri = new URI(targetUriString);
    } catch (URISyntaxException ex) {
        throw new IOException(ex);
    }
    final String method = inRequest.getMethod();
    final HttpEntityEnclosingRequestBase outRequest = new HttpEntityEnclosingRequestBase() {

        @Override
        public String getMethod() {
            return method;
        }

    };
    outRequest.setURI(targetUri);
    String transformerUri = null;
    if (method.equals("POST")) {
        if (!"no-transform".equals(inRequest.getHeader("X-Fusepool-Proxy"))) {
            transformerUri = getTransformerUrl(requestUri);
        }
    }
    final Enumeration<String> headerNames = baseRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        final String headerName = headerNames.nextElement();
        if (headerName.equalsIgnoreCase("Content-Length") || headerName.equalsIgnoreCase("X-Fusepool-Proxy")
                || headerName.equalsIgnoreCase("Transfer-Encoding")) {
            continue;
        }
        final Enumeration<String> headerValues = baseRequest.getHeaders(headerName);
        if (headerValues.hasMoreElements()) {
            final String headerValue = headerValues.nextElement();
            outRequest.setHeader(headerName, headerValue);
        }
        while (headerValues.hasMoreElements()) {
            final String headerValue = headerValues.nextElement();
            outRequest.addHeader(headerName, headerValue);
        }
    }
    final Header[] outRequestHeaders = outRequest.getAllHeaders();
    //slow: outRequest.setEntity(new InputStreamEntity(inRequest.getInputStream()));
    final byte[] inEntityBytes = IOUtils.toByteArray(inRequest.getInputStream());
    if (inEntityBytes.length > 0) {
        outRequest.setEntity(new ByteArrayEntity(inEntityBytes));
    }
    final CloseableHttpResponse inResponse = httpclient.execute(outRequest);
    try {
        outResponse.setStatus(inResponse.getStatusLine().getStatusCode());
        final Header[] inResponseHeaders = inResponse.getAllHeaders();
        final Set<String> setHeaderNames = new HashSet();
        for (Header header : inResponseHeaders) {
            if (setHeaderNames.add(header.getName())) {
                outResponse.setHeader(header.getName(), header.getValue());
            } else {
                outResponse.addHeader(header.getName(), header.getValue());
            }
        }
        final HttpEntity entity = inResponse.getEntity();
        final ServletOutputStream os = outResponse.getOutputStream();
        if (entity != null) {
            //outResponse.setContentType(target);
            final InputStream instream = entity.getContent();
            try {
                IOUtils.copy(instream, os);
            } finally {
                instream.close();
            }
        }
        //without flushing this and no or too little byte jetty return 404
        os.flush();
    } finally {
        inResponse.close();
    }
    if (transformerUri != null) {
        Header locationHeader = inResponse.getFirstHeader("Location");
        if (locationHeader == null) {
            log.warn("Response to POST request to LDPC contains no Location header. URI: " + targetUriString);
        } else {
            startTransformation(locationHeader.getValue(), requestUri, transformerUri, inEntityBytes,
                    outRequestHeaders);
        }
    }
}

From source file:com.aniruddhc.acemusic.player.GMusicHelpers.GMusicClientCalls.java

/*******************************************************************************
 * Attempts to log the user into the "sj" (SkyJam) service using the provided
 * authentication token. The authentication token is unique for each session 
 * and user account. It can be obtained via the GoogleAuthUtil.getToken() 
 * method. See AsyncGoogleMusicAuthenticationTask.java for the current
 * implementation of this process. This method will return true if the login
 * process succeeded. Returns false for any other type of failure.
 * /*from  w ww . ja  v a2  s . c om*/
 * @param context The context that will be used for the login process.
 * @param authToken The authentication token that will be used to login. 
 *******************************************************************************/
public static final boolean login(Context context, String authToken) {

    if (!TextUtils.isEmpty(authToken)) {
        JSONForm form = new JSONForm().close();
        GMusicClientCalls.setAuthorizationHeader(authToken);
        String response = mHttpClient.post(context, "https://play.google.com/music/listen?hl=en&u=0",
                new ByteArrayEntity(form.toString().getBytes()), form.getContentType());

        //Check if the required paramters are null.
        if (response != null) {

            if (getXtCookieValue() != null) {
                return true;
            } else {
                return false;
            }

        } else {
            return false;
        }

    } else {
        return false;
    }

}