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:cn.com.xxutils.volley.toolbox.HttpClientStack.java

/**
 * Creates the appropriate subclass of HttpUriRequest for passed in request.
 *//*  ww  w  . ja  va2s .co  m*/
@SuppressWarnings("deprecation")
/* protected */ static HttpUriRequest createHttpRequest(Request<?> request,
        Map<String, String> additionalHeaders) throws AuthFailureError {
    switch (request.getMethod()) {
    case Request.Method.DEPRECATED_GET_OR_POST: {
        // This is the deprecated way that needs to be handled for backwards compatibility.
        // If the request's post body is null, then the assumption is that the request is
        // GET.  Otherwise, it is assumed that the request is a POST.
        byte[] postBody = request.getPostBody();
        if (postBody != null) {
            HttpPost postRequest = new HttpPost(request.getUrl());
            postRequest.addHeader(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
            HttpEntity entity;
            entity = new ByteArrayEntity(postBody);
            postRequest.setEntity(entity);
            return postRequest;
        } else {
            return new HttpGet(request.getUrl());
        }
    }
    case Request.Method.GET:
        return new HttpGet(request.getUrl());
    case Request.Method.DELETE:
        return new HttpDelete(request.getUrl());
    case Request.Method.POST: {
        HttpPost postRequest = new HttpPost(request.getUrl());
        postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(postRequest, request);
        return postRequest;
    }
    case Request.Method.PUT: {
        HttpPut putRequest = new HttpPut(request.getUrl());
        putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(putRequest, request);
        return putRequest;
    }
    case Request.Method.HEAD:
        return new HttpHead(request.getUrl());
    case Request.Method.OPTIONS:
        return new HttpOptions(request.getUrl());
    case Request.Method.TRACE:
        return new HttpTrace(request.getUrl());
    case Request.Method.PATCH: {
        HttpPatch patchRequest = new HttpPatch(request.getUrl());
        patchRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(patchRequest, request);
        return patchRequest;
    }
    default:
        throw new IllegalStateException("Unknown request method.");
    }
}

From source file:io.github.theguy191919.udpft.net.TCPSenderReceiver.java

@Override
public void run() {
    int sleepFor = 100;
    while (this.running) {
        sleepFor += 10;/*  ww w .ja va  2 s.  c  o m*/
        while (!this.que.isEmpty()) {
            sleepFor -= 50;
            SentContent thing = this.que.poll();
            if (thing == null) {
                break;
            }
            byte[] bytearray = thing.getMessage();
            String url = thing.getUrl();
            this.crypto.encrypt(bytearray);

            //this.printArray("Sending message", bytearray, "End of message");

            HttpPost post = new HttpPost(url);
            //List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            //nvps.add(new BasicNameValuePair("data", ));
            post.setEntity(new ByteArrayEntity(bytearray));
            try {
                HttpResponse response = client.execute(post);
                byte[] reply = EntityUtils.toByteArray(response.getEntity());
                this.messageGotten(reply);
            } catch (IOException ex) {
                Logger.getLogger(TCPSenderReceiver.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        if (sleepFor < 0) {
            sleepFor = 0;
        } else if (sleepFor > 500) {
            sleepFor = 1000;
        }
        try {
            Thread.sleep(sleepFor);
        } catch (InterruptedException ex) {
            Logger.getLogger(Sender.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:wsattacker.plugin.dos.dosExtension.requestSender.Http4RequestSenderImpl.java

public String sendRequestHttpClient(RequestObject requestObject) {
    String strUrl = requestObject.getEndpoint();
    String strXml = requestObject.getXmlMessage();
    byte[] compressedXml = requestObject.getCompressedXML();

    StringBuffer result = new StringBuffer();
    try {/*from  w  ww . j a  v  a 2 s  .c  o m*/
        HttpClient client = new DefaultHttpClient();
        setParamsToClient(client);

        if (useProxy) {
            HttpHost proxy = new HttpHost("sbrproxy1.eur.ad.sag", 3103);
            client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        }

        HttpPost post = new HttpPost(strUrl);
        setHeader(requestObject, post);

        ByteArrayEntity entity;
        if (compressedXml != null) {
            entity = new ByteArrayEntity(compressedXml) {
                @Override
                public void writeTo(OutputStream outstream) throws IOException {
                    super.writeTo(outstream);
                    sendLastByte = System.nanoTime();
                }
            };
        } else {
            entity = new ByteArrayEntity(strXml.getBytes("UTF-8")) {
                @Override
                public void writeTo(OutputStream outstream) throws IOException {
                    super.writeTo(outstream);
                    sendLastByte = System.nanoTime();
                }
            };
        }

        post.setEntity(entity);
        HttpResponse response = client.execute(post);
        receiveFirstByte = System.nanoTime();

        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
    } catch (NumberFormatException e) {

    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // if (!result.toString().contains("tema tis rolod muspi meroL")) {
    // System.out.println(result);
    // }

    return result.toString();
}

From source file:alluxio.underfs.swift.KeystoneV3AccessProvider.java

@Override
public Access authenticate() {

    try {// w  w w  .  j av  a 2  s.c o  m
        String requestBody;
        try {
            // Construct request body
            KeystoneV3Request request = new KeystoneV3Request(
                    new Auth(
                            new Identity(Arrays.asList(AUTH_METHOD),
                                    new Password(new User(mAccountConfig.getUsername(),
                                            mAccountConfig.getPassword()))),
                            new Scope(new Project(mAccountConfig.getTenantName()))));
            requestBody = new ObjectMapper().writeValueAsString(request);
        } catch (JsonProcessingException e) {
            LOG.error("Error processing JSON request: {}", e.getMessage());
            return null;
        }

        try (CloseableHttpClient client = HttpClients.createDefault()) {
            // Send request
            HttpPost post = new HttpPost(mAccountConfig.getAuthUrl());
            post.addHeader("Accept", "application/json");
            post.addHeader("Content-Type", "application/json");
            post.setEntity(new ByteArrayEntity(requestBody.toString().getBytes()));
            try (CloseableHttpResponse httpResponse = client.execute(post)) {
                // Parse response
                int responseCode = httpResponse.getStatusLine().getStatusCode();
                if (responseCode != RESPONSE_OK) {
                    LOG.error("Error with response code {} ", responseCode);
                    return null;
                }
                String token = httpResponse.getFirstHeader("X-Subject-Token").getValue();

                // Parse response body
                try (BufferedReader bufReader = new BufferedReader(
                        new InputStreamReader(httpResponse.getEntity().getContent()))) {
                    String responseBody = bufReader.readLine();
                    KeystoneV3Response response;
                    try {
                        response = new ObjectMapper().readerFor(KeystoneV3Response.class)
                                .readValue(responseBody);
                        // Find endpoints
                        String internalURL = null;
                        String publicURL = null;
                        for (Catalog catalog : response.mToken.mCatalog) {
                            if (catalog.mName.equals("swift") && catalog.mType.equals("object-store")) {
                                for (Endpoint endpoint : catalog.mEndpoints) {
                                    if (endpoint.mRegion.equals(mAccountConfig.getPreferredRegion())) {
                                        if (endpoint.mInterface.equals("public")) {
                                            publicURL = endpoint.mUrl;
                                        } else if (endpoint.mInterface.equals("internal")) {
                                            internalURL = endpoint.mUrl;
                                        }
                                    }
                                }
                            }
                        }
                        // Construct access object
                        KeystoneV3Access access = new KeystoneV3Access(internalURL,
                                mAccountConfig.getPreferredRegion(), publicURL, token);
                        return access;
                    } catch (JsonProcessingException e) {
                        LOG.error("Error processing JSON response: {}", e.getMessage());
                        return null;
                    }
                }
            }
        }
    } catch (IOException e) {
        // Unable to authenticate
        LOG.error("Exception authenticating using KeystoneV3 {}", e.getMessage());
        return null;
    }
}

From source file:com.mobillium.paparasdk.sdk.sampleapp.webservice.PaparaHttpClientStack.java

/**
 * Creates the appropriate subclass of HttpUriRequest for passed in request.
 *//*from ww w.j av a 2  s .c  om*/
@SuppressWarnings("deprecation")
/* protected */ static HttpUriRequest createHttpRequest(Request<?> request,
        Map<String, String> additionalHeaders) throws AuthFailureError {
    switch (request.getMethod()) {
    case Method.DEPRECATED_GET_OR_POST: {
        // This is the deprecated way that needs to be handled for backwards compatibility.
        // If the request's post body is null, then the assumption is that the request is
        // GET.  Otherwise, it is assumed that the request is a POST.
        byte[] postBody = request.getPostBody();
        if (postBody != null) {
            HttpPost postRequest = new HttpPost(request.getUrl());
            postRequest.addHeader(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
            HttpEntity entity;
            entity = new ByteArrayEntity(postBody);
            postRequest.setEntity(entity);
            return postRequest;
        } else {
            return new HttpGet(request.getUrl());
        }
    }
    case Method.GET:
        return new HttpGet(request.getUrl());
    case Method.DELETE:
        OwnHttpDelete deleteRequest = new OwnHttpDelete(request.getUrl());
        deleteRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(deleteRequest, request);
        return deleteRequest;
    case Method.POST: {
        HttpPost postRequest = new HttpPost(request.getUrl());
        postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(postRequest, request);
        return postRequest;
    }
    case Method.PUT: {
        OwnHttpPut deletepOwnHttpPut = new OwnHttpPut(request.getUrl());
        deletepOwnHttpPut.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(deletepOwnHttpPut, request);
        //                HttpPut putRequest = new HttpPut(request.getUrl());
        //                putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        //                setEntityIfNonEmptyBody(putRequest, request);
        return deletepOwnHttpPut;
    }
    case Method.HEAD:
        return new HttpHead(request.getUrl());
    case Method.OPTIONS:
        return new HttpOptions(request.getUrl());
    case Method.TRACE:
        return new HttpTrace(request.getUrl());
    case Method.PATCH: {
        HttpPatch patchRequest = new HttpPatch(request.getUrl());
        patchRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(patchRequest, request);
        return patchRequest;
    }
    default:
        throw new IllegalStateException("Unknown request method.");
    }
}

From source file:com.derson.pumelo.network.volley.toolbox.HttpClientStack.java

/**
 * Creates the appropriate subclass of HttpUriRequest for passed in request.
 *///  w  ww  .j  a va2s. co  m
@SuppressWarnings("deprecation")
/* protected */ static HttpUriRequest createHttpRequest(Request<?> request,
        Map<String, String> additionalHeaders) throws AuthFailureError {
    switch (request.getMethod()) {
    case Request.Method.DEPRECATED_GET_OR_POST: {
        // This is the deprecated way that needs to be handled for backwards compatibility.
        // If the request's post body is null, then the assumption is that the request is
        // GET.  Otherwise, it is assumed that the request is a POST.
        byte[] postBody = request.getPostBody();
        if (postBody != null) {
            HttpPost postRequest = new HttpPost(request.getUrl());
            postRequest.addHeader(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
            HttpEntity entity;
            entity = new ByteArrayEntity(postBody);
            postRequest.setEntity(entity);
            return postRequest;
        } else {
            return new HttpGet(request.getUrl());
        }
    }

    case Request.Method.GET:
        return new HttpGet(request.getUrl());

    case Request.Method.DELETE:
        return new HttpDelete(request.getUrl());
    case Request.Method.POST: {
        HttpPost postRequest = new HttpPost(request.getUrl());
        postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(postRequest, request);
        return postRequest;
    }
    case Request.Method.PUT: {
        HttpPut putRequest = new HttpPut(request.getUrl());
        putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(putRequest, request);
        return putRequest;
    }
    case Request.Method.HEAD:
        return new HttpHead(request.getUrl());
    case Request.Method.OPTIONS:
        return new HttpOptions(request.getUrl());
    case Request.Method.TRACE:
        return new HttpTrace(request.getUrl());
    case Request.Method.PATCH: {
        HttpPatch patchRequest = new HttpPatch(request.getUrl());
        patchRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(patchRequest, request);
        return patchRequest;
    }
    default:
        throw new IllegalStateException("Unknown request method.");
    }
}

From source file:gmusic.api.comm.ApacheConnector.java

@Override
public final synchronized String dispatchPost(URI address, FormBuilder form)
        throws IOException, URISyntaxException {
    HttpPost request = new HttpPost();
    request.setEntity(new ByteArrayEntity(form.getBytes()));

    if (!Strings.isNullOrEmpty(form.getContentType())) {
        request.setHeader("Content-Type", form.getContentType());
    }//from   w  ww.ja v a2 s.c o  m

    String response = EntityUtils.toString(execute(address, request).getEntity());
    if (!isStartup) {
        return response;
    }
    return setupAuthentication(response);
}

From source file:tds.itemscoringengine.web.server.ItemScoringEngineHttpWebHelper.java

public void sendXml(String url, ItemScoreResponse inputData, OutputStream outputData) {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    HttpPost post = new HttpPost(url);
    post.setHeader("Content-Type", "text/xml");
    HttpResponse response = null;/*from   www .ja v  a  2 s .c o m*/
    try {
        inputData.writeXML(out);
        ByteArrayEntity entity = new ByteArrayEntity(out.toByteArray());
        post.setEntity(entity);
        response = _client.execute(post, _contextPool.get());
    } catch (IOException | XMLStreamException e) {
        try {
            outputData.write(String.format("HTTP client through exception: %s", e.getMessage()).getBytes());
        } catch (IOException e1) {
            // Our IOExceptioin through an IOException--bad news!!!
            _logger.error("Output stream encountered an error while attempting to process an error message",
                    e1);
            _logger.error(String.format("Original drror message was \"\"", e.getMessage()));
        }
    }
    if (response != null) {
        HttpEntity responseEntity = response.getEntity();
        if (responseEntity != null) {
            String responseString = "";
            try {
                responseString = EntityUtils.toString(responseEntity);
                outputData.write(responseString.getBytes());
            } catch (IOException e) {
                // Our IOExceptioin through an IOException--bad news!!!
                _logger.error("Output stream encountered an error while attempting to process a reply", e);
                _logger.error(String.format("Original reply content was \"\"", responseString));
            }
            EntityUtils.consumeQuietly(responseEntity);
        }
    }
}

From source file:com.iframe.source.publics.http.volley.toolbox.HttpClientStack.java

/**
 * Creates the appropriate subclass of HttpUriRequest for passed in request.
 *///from ww  w . j a  v a  2 s.c o  m
@SuppressWarnings("deprecation")
/* protected */static HttpUriRequest createHttpRequest(Request<?> request,
        Map<String, String> additionalHeaders) throws AuthFailureError {
    switch (request.getMethod()) {
    case Method.DEPRECATED_GET_OR_POST: {
        // This is the deprecated way that needs to be handled for backwards compatibility.
        // If the request's post body is null, then the assumption is that the request is
        // GET.  Otherwise, it is assumed that the request is a POST.
        byte[] postBody = request.getPostBody();
        if (postBody != null) {
            HttpPost postRequest = new HttpPost(request.getUrl());
            postRequest.addHeader(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
            HttpEntity entity;
            entity = new ByteArrayEntity(postBody);
            postRequest.setEntity(entity);
            return postRequest;
        } else {
            return new HttpGet(request.getUrl());
        }
    }
    case Method.GET:
        return new HttpGet(request.getUrl());
    case Method.DELETE:
        return new HttpDelete(request.getUrl());
    case Method.POST: {
        HttpPost postRequest = new HttpPost(request.getUrl());
        postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(postRequest, request);
        return postRequest;
    }
    case Method.PUT: {
        HttpPut putRequest = new HttpPut(request.getUrl());
        putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(putRequest, request);
        return putRequest;
    }
    case Method.HEAD:
        return new HttpHead(request.getUrl());
    case Method.OPTIONS:
        return new HttpOptions(request.getUrl());
    case Method.TRACE:
        return new HttpTrace(request.getUrl());
    case Method.PATCH: {
        HttpPatch patchRequest = new HttpPatch(request.getUrl());
        patchRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(patchRequest, request);
        return patchRequest;
    }
    default:
        throw new IllegalStateException("Unknown request method.");
    }
}