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:org.surfnet.oaaas.it.ClientCredentialGrantTestIT.java

private InputStream performClientCredentialTokenPost(String username, String password) throws IOException {
    String tokenUrl = String.format("%s/oauth2/token", baseUrl());
    final HttpPost tokenRequest = new HttpPost(tokenUrl);
    String postBody = String.format("grant_type=%s", OAuth2Validator.GRANT_TYPE_CLIENT_CREDENTIALS);

    tokenRequest.setEntity(new ByteArrayEntity(postBody.getBytes()));
    tokenRequest.addHeader("Authorization", authorizationBasic(username, password));
    tokenRequest.addHeader("Content-Type", "application/x-www-form-urlencoded");

    HttpResponse tokenHttpResponse = new DefaultHttpClient().execute(tokenRequest);
    return tokenHttpResponse.getEntity().getContent();
}

From source file:org.apache.edgent.test.connectors.http.HttpTest.java

@Test
public void testPut() throws Exception {
    DirectProvider ep = new DirectProvider();

    Topology topology = ep.newTopology();

    String url = "http://httpbin.org/put";

    TStream<String> stream = topology.strings(url);
    TStream<String> rc = HttpStreams.<String, String>requestsWithBody(stream, HttpClients::noAuthentication,
            t -> HttpPut.METHOD_NAME, t -> t, t -> new ByteArrayEntity(t.getBytes()),
            HttpResponders.inputOn200());

    Tester tester = topology.getTester();

    Condition<List<String>> endCondition = tester.streamContents(rc, url);

    tester.complete(ep, new JsonObject(), endCondition, 10, TimeUnit.SECONDS);

    assertTrue(endCondition.valid());/*from   w ww .  j a va 2 s  . c o  m*/
}

From source file:org.apache.http.localserver.EchoHandler.java

/**
 * Handles a request by echoing the incoming request entity.
 * If there is no request entity, an empty document is returned.
 *
 * @param request   the request//  w  w  w  .  j a  v a2s.  com
 * @param response  the response
 * @param context   the context
 *
 * @throws HttpException    in case of a problem
 * @throws IOException      in case of an IO problem
 */
public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context)
        throws HttpException, IOException {

    String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
    if (!"GET".equals(method) && !"POST".equals(method) && !"PUT".equals(method)) {
        throw new MethodNotSupportedException(method + " not supported by " + getClass().getName());
    }

    HttpEntity entity = null;
    if (request instanceof HttpEntityEnclosingRequest)
        entity = ((HttpEntityEnclosingRequest) request).getEntity();

    // For some reason, just putting the incoming entity into
    // the response will not work. We have to buffer the message.
    byte[] data;
    if (entity == null) {
        data = new byte[0];
    } else {
        data = EntityUtils.toByteArray(entity);
    }

    ByteArrayEntity bae = new ByteArrayEntity(data);
    if (entity != null) {
        bae.setContentType(entity.getContentType());
    }
    entity = bae;

    response.setStatusCode(HttpStatus.SC_OK);
    response.setEntity(entity);

}

From source file:org.dthume.spring.http.client.httpcomponents.HttpComponentsClientHttpRequest.java

private void addBody(final HttpRequest request, final byte[] output) {
    if (request instanceof HttpEntityEnclosingRequest) {
        final HttpEntity entity = new ByteArrayEntity(output);
        ((HttpEntityEnclosingRequest) request).setEntity(entity);
    }//from   ww w . j  av  a  2s  .  c o m
}

From source file:com.github.yongchristophertang.engine.web.request.HttpRequestBuilders.java

/**
 * {@inheritDoc}/*from ww  w  .  ja  v a2s  .  c  o m*/
 */
@Override
public HttpRequest buildRequest() throws Exception {
    URIBuilder builder = new URIBuilder(uriTemplate);
    builder.addParameters(parameters);
    Header[] heads = new Header[headers.size()];
    httpRequest.setHeaders(headers.toArray(heads));
    ((HttpRequestBase) httpRequest).setURI(builder.build());
    postProcessors.stream().forEach(p -> httpRequest = p.postProcessRequest(httpRequest));

    // The priorities for each content type are bytesContent > stringContent > bodyParameters
    if (bytesContent != null && bytesContent.length > 0) {
        ((HttpEntityEnclosingRequestBase) httpRequest).setEntity(new ByteArrayEntity(bytesContent));
    } else if (stringContent != null && stringContent.length() > 0) {
        ((HttpEntityEnclosingRequestBase) httpRequest).setEntity(new StringEntity(stringContent, "UTF-8"));
    } else if (bodyParameters.size() > 0) {
        ((HttpEntityEnclosingRequestBase) httpRequest)
                .setEntity(new UrlEncodedFormEntity(bodyParameters, "UTF-8"));
    }
    return httpRequest;
}

From source file:com.eTilbudsavis.etasdk.network.impl.DefaultHttpNetwork.java

private static void setEntity(HttpEntityEnclosingRequestBase httpRequest, Request<?> request) {
    byte[] body = request.getBody();
    if (body != null) {
        HttpEntity entity = new ByteArrayEntity(body);
        httpRequest.setEntity(entity);/*from   w w w  .  j  a v  a 2  s  . c  o  m*/
        httpRequest.setHeader(HeaderUtils.CONTENT_TYPE, request.getBodyContentType());
    }
}

From source file:at.ac.tuwien.dsg.elasticdaasclient.utils.RestfulWSClient.java

public String callPutMethodObj(Object obj) {
    String rs = "";
    String returnObj = null;//w w w  .j  a  v a2s  .  c  o m

    try {

        String xmlString = "";

        xmlString = JAXBUtils.marshal(obj, obj.getClass());
        System.out.println(xmlString);

        Logger.getLogger(RestfulWSClient.class.getName()).log(Level.INFO, "Connection .. " + url);

        HttpPut request = new HttpPut(url);
        request.addHeader("content-type", "application/xml; charset=utf-8");
        request.addHeader("Accept", "application/xml, multipart/related");
        HttpEntity entity = new ByteArrayEntity(xmlString.getBytes("UTF-8"));

        request.setEntity(entity);

        HttpResponse methodResponse = this.getHttpClient().execute(request);

        int statusCode = methodResponse.getStatusLine().getStatusCode();

        Logger.getLogger(RestfulWSClient.class.getName()).log(Level.INFO, "Status Code: " + statusCode);
        BufferedReader rd = new BufferedReader(new InputStreamReader(methodResponse.getEntity().getContent()));

        StringBuilder result = new StringBuilder();
        String line;
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }

        rs = result.toString();

        //  returnObj = (T) JAXBUtils.unmarshal(rs, returnObj.getClass());

        // System.out.println("Response String: " + result.toString());
    } catch (Exception ex) {
        System.out.println("Exception: " + ex.toString());
    }
    return returnObj;
}

From source file:com.lenovo.h2000.services.LicenseServiceImpl.java

@Override
public String upload(byte[] fileBytes, Map<String, String> headers) throws Exception {
    Map<String, String> params = new HashMap<String, String>();

    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(
            HttpConfig.parseBaseUrl(headers) + "license/import" + "?" + TypeUtil.mapToString(params));

    String responseBody = "";
    DataInputStream in = null;// ww  w.j a  v a2 s. co m
    try {

        ByteArrayEntity requestEntity = new ByteArrayEntity(fileBytes);
        requestEntity.setContentEncoding("UTF-8");
        requestEntity.setContentType("application/octet-stream");
        httpPost.setEntity(requestEntity);
        HttpResponse response = httpClient.execute(httpPost);
        response.setHeader(HttpHeaders.CONTENT_TYPE, "application/json; charset=UTF-8");
        HttpEntity responseEntity = response.getEntity();
        responseBody = EntityUtils.toString(responseEntity);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        _logger.error("throwing HttpClientUtil.doPost ClientProtocolException with " + e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        _logger.error("throwing HttpClientUtil.doPost IOException with " + e.getMessage());
    } finally {
        httpClient.close();
        if (in != null) {
            in.close();
        }
    }
    return responseBody;
}

From source file:com.google.dataconnector.client.fetchrequest.HttpFetchStrategy.java

/**
 * Based on the inbound request type header, determine the correct http
 * method to use.  If a method cannot be determined (or not specified),
 * HTTP GET is attempted./*from  w  w  w .  ja v  a 2s.  c  om*/
 */
HttpRequestBase getMethod(FetchRequest request) {
    String method = null;
    for (MessageHeader h : request.getHeadersList()) {
        if ("x-sdc-http-method".equalsIgnoreCase(h.getKey())) {
            method = h.getValue().toUpperCase();
        }
    }

    LOG.info(request.getId() + ": method=" + method + ", resource=" + request.getResource()
            + ((request.hasContents()) ? ", payload_size=" + request.getContents().size() : ""));

    if (method == null) {
        LOG.info(request.getId() + ": No http method specified. Default to GET.");
        method = "GET";
    }

    if ("GET".equals(method)) {
        return new HttpGet(request.getResource());
    }
    if ("POST".equals(method)) {
        HttpPost httpPost = new HttpPost(request.getResource());
        if (request.hasContents()) {
            LOG.debug(request.getId() + ": Content = " + new String(request.getContents().toByteArray()));
            httpPost.setEntity(new ByteArrayEntity(request.getContents().toByteArray()));
        }
        return httpPost;
    }
    if ("PUT".equals(method)) {
        HttpPut httpPut = new HttpPut(request.getResource());
        if (request.hasContents()) {
            LOG.debug(request.getId() + ": Content = " + new String(request.getContents().toByteArray()));
            httpPut.setEntity(new ByteArrayEntity(request.getContents().toByteArray()));
        }
        return httpPut;
    }
    if ("DELETE".equals(method)) {
        return new HttpDelete(request.getResource());
    }
    if ("HEAD".equals(method)) {
        return new HttpHead(request.getResource());
    }
    LOG.info(request.getId() + ": Unknown method " + method);
    return null;
}

From source file:net.instantcom.mm7.DeliverReqTest.java

@Test
public void readCaiXinDatafromHW() throws IOException, MM7Error {
    String ct = "multipart/related; boundary=\"--NextPart_0_9094_20600\"; type=text/xml";
    InputStream in = DeliverReq.class.getResourceAsStream("caixin.txt");
    DeliverReq req = (DeliverReq) MM7Response.load(in, ct, new MM7Context());

    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost post = null;/*from   w  w  w  .  j  a v a  2 s . co m*/
    try {
        post = new HttpPost("http://127.0.0.1:8081/mm7serv/10085receiver");
        //post = new HttpPost("http://42.96.185.95:8765");
        post.addHeader("Content-Type", req.getSoapContentType());
        post.addHeader("SOAPAction", "");
        ByteArrayOutputStream byteos = new ByteArrayOutputStream();
        MM7Message.save(req, byteos, new MM7Context());
        post.setEntity(new ByteArrayEntity(byteos.toByteArray()));
        HttpResponse resp = httpclient.execute(post);
        HttpEntity entity = resp.getEntity();
        String message = EntityUtils.toString(entity, "utf-8");
        System.out.println(message);
    } catch (Exception e) {

    } finally {
        if (post != null)
            post.releaseConnection();
    }

    for (Content c : req.getContent()) {
        ContentType ctype = new ContentType(c.getContentType());
        if (ctype.getPrimaryType().equals("image")) {
            BinaryContent image = (BinaryContent) c;
            String fileName = DeliverReq.class.getResource("caixin.txt").getFile() + ".jpg";
            System.out.println(fileName);
            Base64 base64 = new Base64();
            FileUtils.writeByteArrayToFile(new File(fileName), base64.encode(image.getData()));
        }
    }
    ByteArrayOutputStream byteos = new ByteArrayOutputStream();
    MM7Message.save(req, byteos, new MM7Context());

    req = (DeliverReq) MM7Response.load(new ByteArrayInputStream(byteos.toByteArray()),
            req.getSoapContentType(), new MM7Context());
    assertEquals("+8618703815655", req.getSender().toString());
}