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.zywx.wbpalmstar.platform.push.report.PushReportHttpClient.java

public static String sendPostData(String data, String url, Context mCtx) {

    // HttpUriRequest httpRequest = new HttpPost(url);
    PushReportUtility.log("url = " + url);
    HttpPost post = new HttpPost(url);
    HttpClient httpClient = getSSLHttpClient(mCtx);
    // Post???NameValuePair[]
    // ???request.getParameter("name")
    // List<NameValuePair> params = new ArrayList<NameValuePair>();
    // params.add(new BasicNameValuePair("name", data));
    BDebug.d("debug", "data == " + data);
    PushReportUtility.log("data == " + data);
    HttpResponse httpResponse = null;/*w  ww.ja v a2s.  c o  m*/
    post.setHeader("Accept", "*/*");
    // HttpClient httpClient = null;
    try {
        MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        // ?HTTP request

        post.setEntity(new ByteArrayEntity(data.getBytes()));
        // ?HTTP response
        // httpClient = getSSLHttpClient();
        httpResponse = httpClient.execute(post);
        // ??200 ok
        int responesCode = httpResponse.getStatusLine().getStatusCode();
        BDebug.d("debug", "responesCode == " + responesCode);
        PushReportUtility.log("responesCode == " + responesCode);
        if (responesCode == 200) {
            // ?
            String res = EntityUtils.toString(httpResponse.getEntity());
            PushReportUtility.log("res == " + res);
            return res;
        } else {
            System.out.println(EntityUtils.toString(httpResponse.getEntity()));
        }

    } catch (Exception e) {
        PushReportUtility.log("Exception == " + e.getMessage());
        e.printStackTrace();
    } finally {
        if (post != null) {
            post.abort();
            post = null;
        }
        if (httpResponse != null) {
            httpResponse = null;
        }
        if (httpClient != null) {
            httpClient.getConnectionManager().shutdown();
            httpClient = null;
        }
    }
    return null;
}

From source file:com.mlohr.hvvgti.ApiClient.java

private BaseResponse executeApiRequest(BaseRequest apiRequest) throws ApiException {
    HttpPost httpRequest = new HttpPost(getBaseUri() + apiRequest.getUriPart());
    httpRequest.setHeader(new BasicHeader("Content-Type", "application/json"));
    httpRequest.setHeader(new BasicHeader("Accept", "application/json"));
    // TODO configure user agent
    httpRequest.setHeader(new BasicHeader("geofox-auth-type", getSignatureAlgorithm().getAlgorithmString()));
    httpRequest.setHeader(new BasicHeader("geofox-auth-user", authUser));
    httpRequest.setHeader(new BasicHeader("geofox-auth-signature", generateSignature(apiRequest.getBody())));
    httpRequest.setEntity(new ByteArrayEntity(apiRequest.getBody().toString().getBytes()));
    try {/*w ww .j ava 2 s.c  o  m*/
        HttpResponse httpResponse = httpClient.execute(httpRequest);
        BasicResponseHandler responseHandler = new BasicResponseHandler();
        String responseBody = responseHandler.handleResponse(httpResponse);
        return new BaseResponse(responseBody);
    } catch (HttpResponseException e) {
        throw new ApiException("Error sending HTTP request", e.getStatusCode(), e);
    } catch (ClientProtocolException e) {
        throw new ApiException("Error sending HTTP request", e);
    } catch (JSONException e) {
        throw new ApiException("Error parsing JSON response", e);
    } catch (IOException e) {
        throw new ApiException(e);
    }
}

From source file:com.azure.webapi.ServiceFilterRequestImpl.java

@Override
public void setContent(byte[] content) throws Exception {
    ((HttpEntityEnclosingRequestBase) mRequest).setEntity(new ByteArrayEntity(content));
    mContent = content;/* w  w w .  j ava 2s  .  co m*/
}

From source file:net.sf.jasperreports.phantomjs.ProcessConnection.java

public String runRequest(String data) {
    HttpPost httpPost = new HttpPost(process.getListenURI());
    HttpEntity postEntity = new ByteArrayEntity(data.getBytes(StandardCharsets.UTF_8));
    httpPost.setEntity(postEntity);//from  w  ww.ja  va  2  s.  c o  m

    if (log.isDebugEnabled()) {
        log.debug(process.getId() + " executing HTTP at " + process.getListenURI());
    }

    try (CloseableHttpResponse response = httpClient.execute(httpPost)) {

        StatusLine status = response.getStatusLine();
        if (log.isDebugEnabled()) {
            log.debug(process.getId() + " HTTP response status " + status);
        }

        HttpEntity entity = response.getEntity();
        if (entity == null) {
            throw new JRRuntimeException("Empty from PhantomJS");
        }

        if (status.getStatusCode() >= 300) {
            if (entity.getContentType() != null && entity.getContentType().getValue() != null
                    && entity.getContentType().getValue().startsWith("text/plain")) {
                String responseContents = EntityUtils.toString(entity, StandardCharsets.UTF_8);
                log.error("PhantomJS process " + process.getId() + " error: " + responseContents);
            } else {
                EntityUtils.consumeQuietly(entity);
            }
            throw new JRRuntimeException("Unexpected status " + status + " from PhantomJS");
        }

        byte[] responseData;
        try (InputStream responseStream = entity.getContent()) {
            responseData = JRLoader.loadBytes(responseStream);
        }

        //TODO lucianc return the bytes
        return new String(responseData, StandardCharsets.UTF_8);
    } catch (SocketTimeoutException e) {
        log.error(process.getId() + " request timed out");
        throw new RequestTimeoutException(e);
    } catch (JRException | IOException e) {
        throw new JRRuntimeException(e);
    }
}

From source file:org.wso2.am.integration.tests.rest.MalformedRequestTest.java

@Test(groups = "wso2.am", description = "Check if a malformed request breaks the system")
public void testMalformedPostWithMessageBuilding() {

    HttpClient httpclient = HttpClientBuilder.create().build();
    HttpPost httppost = new HttpPost(getGatewayURLNhttp() + "response");

    httppost.addHeader(new Header() {
        @Override//from   www. j ava  2 s.  c om
        public String getName() {
            return "Content-Type";
        }

        @Override
        public String getValue() {
            return "application/xml";
        }

        @Override
        public HeaderElement[] getElements() throws ParseException {
            return new HeaderElement[0];
        }
    });

    String malformedBody = "<request>Request<request>";
    HttpResponse response = null;

    try {
        HttpEntity entity = new ByteArrayEntity(malformedBody.getBytes("UTF-8"));
        httppost.setEntity(entity);
        response = httpclient.execute(httppost);
    } catch (ClientProtocolException e) {
        //Fail the test case.
        Assert.assertTrue(false, e.getMessage());
    } catch (UnsupportedEncodingException e) {
        //Fail the test case.
        Assert.assertTrue(false, e.getMessage());
    } catch (IOException e) {
        //Fail the test case.
        Assert.assertTrue(false, e.getMessage());
    }

    Assert.assertNotNull(response, "Received null response for malformed post");

    Assert.assertEquals(response.getStatusLine().getStatusCode(), 500,
            "Did not receive an http 500 for the malformed request");
}

From source file:com.lovebridge.library.volley.toolbox.HttpClientStack.java

/**
 * Creates the appropriate subclass of HttpUriRequest for passed in request.
 *///from ww w.j  a va  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:
        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.");
    }
}

From source file:no.ntnu.idi.socialhitchhiking.client.RequestTask.java

/**
 * Constructor for preparing request to server
 * @param addr/*from  w w  w .jav  a  2 s .  co  m*/
 * @param xml
 */
private RequestTask(final String addr, String xml) {
    this.addr = addr;
    httpclient = new DefaultHttpClient();
    response = null;
    RequestLine line = new BasicRequestLine("POST", "/Freerider_backend/Servlet",
            new ProtocolVersion("HTTP", 1, 1));
    entityRequest = new BasicHttpEntityEnclosingRequest(line);
    try {

        entity = new ByteArrayEntity(xml.getBytes("ISO-8859-1"));
        entityRequest.setEntity(entity);
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
}

From source file:com.huoqiu.framework.rest.HttpComponentsClientHttpRequest.java

@Override
public ClientHttpResponse executeInternal(HttpHeaders headers, byte[] bufferedOutput) throws IOException {
    for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
        String headerName = entry.getKey();
        if (!headerName.equalsIgnoreCase(HTTP.CONTENT_LEN)
                && !headerName.equalsIgnoreCase(HTTP.TRANSFER_ENCODING)) {
            for (String headerValue : entry.getValue()) {
                this.httpRequest.addHeader(headerName, headerValue);
            }/*  ww w . j  a va2 s .c  o  m*/
        }
    }
    if (this.httpRequest instanceof HttpEntityEnclosingRequest) {
        HttpEntityEnclosingRequest entityEnclosingReq = (HttpEntityEnclosingRequest) this.httpRequest;
        HttpEntity requestEntity = new ByteArrayEntity(bufferedOutput);
        entityEnclosingReq.setEntity(requestEntity);
    }
    HttpResponse httpResponse = httpClient.execute(this.httpRequest, this.httpContext);
    return new HttpComponentsClientHttpResponse(httpResponse);
}

From source file:net.gcolin.httpquery.HttpHandlerImpl.java

@Override
public Request post(String uri, byte[] data) {
    HttpPost post = new HttpPost(uri);
    post.setEntity(new ByteArrayEntity(data));
    return new RequestImpl(post);
}