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.wso2.dss.integration.test.sparql.SPARQLServiceTestCase.java

public Object[] sendPOST(String endpoint, String content, Map<String, String> headers) throws IOException {
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(endpoint);
    httpClient.getParams().setParameter("http.socket.timeout", 300000);
    for (String headerType : headers.keySet()) {
        httpPost.setHeader(headerType, headers.get(headerType));
    }// w  w w.j a  v  a  2  s  .  c  o m
    if (content != null) {
        HttpEntity httpEntity = new ByteArrayEntity(content.getBytes("UTF-8"));
        if (headers.get("Content-Type") == null) {
            httpPost.setHeader("Content-Type", "application/json");
        }
        httpPost.setEntity(httpEntity);
    }
    HttpResponse httpResponse = httpClient.execute(httpPost);
    if (httpResponse.getEntity() != null) {
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(httpResponse.getEntity().getContent()));
        String inputLine;
        StringBuilder response = new StringBuilder();
        while ((inputLine = reader.readLine()) != null) {
            response.append(inputLine);
        }
        reader.close();
        return new Object[] { httpResponse.getStatusLine().getStatusCode(), response.toString() };
    } else {
        return new Object[] { httpResponse.getStatusLine().getStatusCode() };
    }
}

From source file:org.exoplatform.social.client.api.util.SocialHttpClientSupport.java

/**
 * Invokes the social rest service via Post method
 * @param targetURL //w w w .  j a  v  a2 s  .  com
 * @param authPolicy POLICY.NO_AUTH/POLICY.BASIC_AUTH
 * @param params HttpParams for Request
 * @return
 * @throws IOException
 * @throws ClientProtocolException
 */
public static HttpResponse executePost(String targetURL, POLICY authPolicy, HttpParams params, Model model)
        throws SocialHttpClientException {
    HttpHost targetHost = new HttpHost(SocialClientContext.getHost(), SocialClientContext.getPort(),
            SocialClientContext.getProtocol());
    SocialHttpClient httpClient = SocialHttpClientImpl.newInstance();

    if (POLICY.BASIC_AUTH == authPolicy) {
        try {
            httpClient.setBasicAuthenticateToRequest();
        } catch (SocialClientLibException e) {
            throw new SocialHttpClientException(e.getMessage(), e);
        }
    }

    HttpPost httpPost = new HttpPost(targetURL);
    Header header = new BasicHeader("Content-Type", "application/json");
    httpPost.setHeader(header);
    //Post method with the HttpParams
    if (params != null) {
        httpPost.setParams(params);
    }
    try {

        //Provides when uses post so does not have any data.
        byte[] postData = convertModelToByteArray(model);
        if (postData != null) {
            ByteArrayEntity entity = new ByteArrayEntity(convertModelToByteArray(model));
            httpPost.setEntity(entity);
        }
        HttpResponse response = httpClient.execute(targetHost, httpPost);

        //handleError(response);
        //Debugging in the devlopment mode
        if (SocialClientContext.isDeveloping()) {
            dumpHttpResponsetHeader(response);
            dumpContent(response);
        }
        return response;
    } catch (ClientProtocolException cpex) {
        throw new SocialHttpClientException(cpex.toString(), cpex);
    } catch (IOException ioex) {
        throw new SocialHttpClientException(ioex.toString(), ioex);
    }

}

From source file:com.tremolosecurity.proxy.postProcess.PushRequestProcess.java

@Override
public void postProcess(HttpFilterRequest req, HttpFilterResponse resp, UrlHolder holder, HttpFilterChain chain)
        throws Exception {
    boolean isText;

    HashMap<String, String> uriParams = (HashMap<String, String>) req.getAttribute("TREMOLO_URI_PARAMS");

    StringBuffer proxyToURL = new StringBuffer();

    proxyToURL.append(holder.getProxyURL(uriParams));

    boolean first = true;
    for (NVP p : req.getQueryStringParams()) {
        if (first) {
            proxyToURL.append('?');
            first = false;//from  w  w  w  .  j  av a  2s .  c o  m
        } else {
            proxyToURL.append('&');
        }

        proxyToURL.append(p.getName()).append('=').append(URLEncoder.encode(p.getValue(), "UTF-8"));
    }

    HttpEntity entity = null;

    if (req.isMultiPart()) {

        MultipartEntityBuilder mpeb = MultipartEntityBuilder.create()
                .setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

        for (String name : req.getFormParams()) {

            /*if (queryParams.contains(name)) {
               continue;
            }*/

            for (String val : req.getFormParamVals(name)) {
                //ent.addPart(name, new StringBody(val));
                mpeb.addTextBody(name, val);
            }

        }

        HashMap<String, ArrayList<FileItem>> files = req.getFiles();
        for (String name : files.keySet()) {
            for (FileItem fi : files.get(name)) {
                //ent.addPart(name, new InputStreamBody(fi.getInputStream(),fi.getContentType(),fi.getName()));

                mpeb.addBinaryBody(name, fi.get(), ContentType.create(fi.getContentType()), fi.getName());

            }
        }

        entity = mpeb.build();

    } else if (req.isParamsInBody()) {
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();

        for (String paramName : req.getFormParams()) {

            for (String val : req.getFormParamVals(paramName)) {

                formparams.add(new BasicNameValuePair(paramName, val));
            }
        }

        entity = new UrlEncodedFormEntity(formparams, "UTF-8");
    } else {

        byte[] msgData = (byte[]) req.getAttribute(ProxySys.MSG_BODY);
        ByteArrayEntity bentity = new ByteArrayEntity(msgData);
        bentity.setContentType(req.getContentType());

        entity = bentity;
    }

    MultipartRequestEntity frm;

    CloseableHttpClient httpclient = this.getHttp(proxyToURL.toString(), req.getServletRequest(),
            holder.getConfig());

    //HttpPost httppost = new HttpPost(proxyToURL.toString());
    HttpEntityEnclosingRequestBase httpMethod = new EntityMethod(req.getMethod(), proxyToURL.toString());//this.getHttpMethod(proxyToURL.toString());

    setHeadersCookies(req, holder, httpMethod, proxyToURL.toString());

    httpMethod.setEntity(entity);

    HttpContext ctx = (HttpContext) req.getSession().getAttribute(ProxySys.HTTP_CTX);
    HttpResponse response = httpclient.execute(httpMethod, ctx);

    postProcess(req, resp, holder, response, proxyToURL.toString(), chain, httpMethod);

}

From source file:com.couchbase.capi.TestCAPI.java

public void testRevsDiffDoesNotExist() throws Exception {
    HttpClient client = getClient();//  ww  w  . j a v a  2  s  .co m

    HttpPost request = new HttpPost(String.format("http://localhost:%d/doesnotexist/_revs_diff", port));

    List<String> revs = new ArrayList<String>();
    revs.add("1-abc");
    revs.add("2-def");
    Map<String, Object> revsDiff = new HashMap<String, Object>();
    revsDiff.put("12345", revs);

    request.setEntity(new ByteArrayEntity(mapper.writeValueAsBytes(revsDiff)));
    HttpResponse response = client.execute(request);

    Assert.assertEquals(404, response.getStatusLine().getStatusCode());
}

From source file:com.gistlabs.mechanize.cache.inMemory.InMemoryCacheEntry.java

@Override
public HttpResponse head() {
    BasicHttpResponse response = new BasicHttpResponse(this.response.getStatusLine());
    Header[] allHeaders = this.response.getAllHeaders();
    for (Header allHeader : allHeaders)
        response.addHeader(allHeader);// ww w .ja v  a 2 s.  c  om
    response.setEntity(new ByteArrayEntity(new byte[] {}));
    return response;
}

From source file:com.comcast.cim.rest.client.xhtml.TestXhtmlResponseHandler.java

@Test
public void testPopulatesRequestContextInResult() throws Exception {
    HttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
    resp.setHeader("Content-Type", "application/xhtml+xml;charset=utf-8");
    String xhtml = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML " + "1.0 Transitional//EN\" "
            + "\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">"
            + "<html xmlns=\"http://www.w3.org/1999/xhtml\" "
            + "xml:lang=\"en\" lang=\"en\"><head/><body/></html>";
    byte[] bytes = xhtml.getBytes();
    resp.setEntity(new ByteArrayEntity(bytes));
    resp.setHeader("Content-Length", "" + bytes.length);

    XhtmlApplicationState result = impl.handleResponse(resp);
    Assert.assertSame(context, result.getContext());
}

From source file:org.keycloak.authorization.client.util.HttpMethod.java

public HttpMethod<R> json(byte[] entity) {
    this.builder.addHeader("Content-Type", "application/json");
    this.builder.setEntity(new ByteArrayEntity(entity));
    return this;
}

From source file:edu.umn.msi.tropix.transfer.http.server.embedded.JettyServerTest.java

@Test(groups = "unit")
public void init() throws Exception {
    final int port = 61948;
    final JettyServer jettyServer = new JettyServer(port);
    final TestHandlerImpl handler = new TestHandlerImpl();
    jettyServer.setHandler(handler);//w w w  .j av  a  2 s . co m
    init(jettyServer);
    assert jettyServer.getPort() == 61948 : jettyServer.getPort();

    final ByteArrayOutputStream stream = new ByteArrayOutputStream();
    final HttpClient client = new DefaultHttpClient();
    final HttpGet httpget = new HttpGet("http://127.0.0.1:" + port);
    final HttpResponse response = client.execute(httpget);
    try {
        assert response.getStatusLine().getStatusCode() == 200;
        IO_UTILS.copy(response.getEntity().getContent(), stream);
    } finally {
        httpget.abort();
    }
    assert new String(stream.toByteArray()).equals("Output");

    final HttpPost httppost = new HttpPost("http://127.0.0.1:" + port);
    final ByteArrayEntity entity = new ByteArrayEntity("Input".getBytes());
    httppost.setEntity(entity);
    final HttpResponse postResponse = client.execute(httppost);
    try {
        assert postResponse.getStatusLine().getStatusCode() == 200;
    } finally {
        httppost.abort();
    }

    assert new String(handler.inputs.get(1)).equals("Input");
    jettyServer.destroy();
}

From source file:org.n52.geoar.data.sos.SOSDataSource.java

@PostConstruct
public void init() {
    if (serviceUrl == null || (capabilitiesFuture != null && capabilitiesFuture.isDone())) {
        return;/*  w  w w .  java 2  s. c  o m*/
    }

    // TODO maybe use SOSUtils

    Callable<ServiceIdentifiation> capabilitiesCallable = new Callable<ServiceIdentifiation>() {
        @Override
        public ServiceIdentifiation call() throws Exception {
            try {
                HttpPost httpPost = new HttpPost(serviceUrl);
                httpPost.setHeader("Content-Type", "text/xml");
                httpPost.setHeader("Accept", "text/xml");
                ByteArrayEntity requestEntity = new ByteArrayEntity(
                        SOSRequest.createCapabilitiesRequestXML().toByteArray());
                httpPost.setEntity(requestEntity);

                HttpResponse response = mHttpClient.execute(httpPost);
                HttpEntity responseEntity = response.getEntity();
                InputStream content = responseEntity.getContent();
                CapabilitiesResult result = SOSResponse.processCapabilitiesResponse(content, serviceUrl);
                content.close();
                return result.getServiceIdentifiation();
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e.getMessage());
            }
        }
    };
    capabilitiesFuture = capabilitiesExecutor.submit(capabilitiesCallable);
}