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.n52.geoar.data.sos.SOSDataSource.java

private List<FOI> getFeatureOfInterest(GeoLocationRect bbox) throws Exception {
    HttpPost httpPost = new HttpPost(serviceUrl);
    httpPost.setHeader("Content-Type", "text/xml");
    httpPost.setHeader("Accept", "text/xml");

    boolean useEpsgVer = useEpsgVersion != null ? useEpsgVersion.booleanValue() : true;
    // Try with epsg version first or use previous decision
    ByteArrayEntity requestEntity = new ByteArrayEntity(
            SOSRequest.createFeatureOfInterestRequestXML(bbox, useEpsgVer).toByteArray());
    httpPost.setEntity(requestEntity);/* w  w  w .j a  va2s  . com*/

    HttpResponse response = mHttpClient.execute(httpPost);
    HttpEntity responseEntity = response.getEntity();
    List<FOI> fois = null;
    InputStream content = responseEntity.getContent();
    try {
        fois = SOSResponse.processFeatureOfInterestResponse(content, serviceUrl);
    } catch (OWSException e) {
        if (useEpsgVer && e.getTitle().equals("InvalidParameterValue")
                && e.getMessage().contains("schema:urn:ogc:def:crs:EPSG:number")) {
            // Used epsg version and received ExceptionReport about srs name
            // convention -> use fallback and try again
            useEpsgVersion = false;
            fois = getFeatureOfInterest(bbox);
        } else {
            throw e;
        }
    } finally {
        content.close();
    }
    // If request succeeded
    if (useEpsgVersion == null) {
        useEpsgVersion = true;
    }
    return fois;
}

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

@Test
public void sendrequest() throws IOException, MM7Error {
    String ct = "multipart/related; boundary=\"Nokia-mm-messageHandler-BoUnDaRy-=_-735647067\"; type=text/xml";
    InputStream in = DeliverReq.class.getResourceAsStream("deliver-req6-hw.txt");
    DeliverReq req = (DeliverReq) MM7Response.load(in, ct, new MM7Context());
    ByteArrayOutputStream byteos = new ByteArrayOutputStream();
    MM7Message.save(req, byteos, new MM7Context());

    req = (DeliverReq) MM7Response.load(new ByteArrayInputStream(byteos.toByteArray()),
            req.getSoapContentType(), new MM7Context());
    assertEquals(null, req.getVasId());//from w ww .  ja va 2  s.  co m
    assertEquals("910000", req.getRelayServerId());
    assertEquals("13951900000", req.getSender().toString());
    assertEquals("This is a test", req.getSubject());
    assertEquals(Priority.LOW, req.getPriority());

    Content text = new TextContent("13951900000139519000001395190000013951900000");
    req.getContent().addParts(text);

    MM7Message.save(req, System.out, new MM7Context());
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost post = null;
    try {
        post = new HttpPost("http://127.0.0.1:55603");
        //post = new HttpPost("http://42.96.185.95:8765");
        post.addHeader("Content-Type", req.getSoapContentType());
        post.addHeader("SOAPAction", "");
        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();
    }
}

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

public static HttpResponse httpsPost(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 SSLClient();
    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()));
    }//w w  w.  jav a2 s . c o m

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

    }

    return httpClient.execute(post);
}

From source file:com.kixeye.relax.AsyncRestClient.java

/**
 * @see com.kixeye.relax.RestClient#put(java.lang.String, java.lang.String, java.lang.String, I, java.lang.Object)
 *///from  w  ww  .  j a  v  a 2 s  .  co m
@Override
public <I> HttpPromise<HttpResponse<Void>> put(String path, String contentTypeHeader, String acceptHeader,
        I requestObject, Map<String, List<String>> additonalHeaders, Object... pathVariables)
        throws IOException {
    HttpPromise<HttpResponse<Void>> promise = new HttpPromise<>();

    HttpPost request = new HttpPost(UrlUtils.expand(uriPrefix + path, pathVariables));
    if (requestObject != null) {
        request.setEntity(new ByteArrayEntity(serDe.serialize(contentTypeHeader, requestObject)));
    }

    if (contentTypeHeader != null) {
        request.setHeader("Content-Type", contentTypeHeader);
    }

    if (acceptHeader != null) {
        request.setHeader("Accept", acceptHeader);
    }

    if (additonalHeaders != null && !additonalHeaders.isEmpty()) {
        for (Entry<String, List<String>> header : additonalHeaders.entrySet()) {
            for (String value : header.getValue()) {
                request.addHeader(header.getKey(), value);
            }
        }
    }

    httpClient.execute(request, new AsyncRestClientResponseCallback<>(null, promise));

    return promise;
}

From source file:cn.tc.ulife.platform.msg.http.util.HttpUtil.java

/**
 * HTTP POST /*from w w  w  . j av a  2  s  .co  m*/
 * @param host
 * @param path
 * @param connectTimeout
 * @param headers
 * @param querys
 * @param bodys
 * @param signHeaderPrefixList
 * @param appKey
 * @param appSecret
 * @return
 * @throws Exception
 */
public static Response httpPost(String host, String path, int connectTimeout, Map<String, String> headers,
        Map<String, String> querys, byte[] bodys, List<String> signHeaderPrefixList, String appKey,
        String appSecret) throws Exception {
    headers = initialBasicHeader(HttpMethod.POST, path, headers, querys, null, signHeaderPrefixList, appKey,
            appSecret);

    HttpClient httpClient = wrapClient(host);
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, getTimeout(connectTimeout));

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

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

    return convert(httpClient.execute(post));
}

From source file:eu.esdihumboldt.hale.io.geoserver.rest.AbstractResourceManager.java

/**
 * @see eu.esdihumboldt.hale.io.geoserver.rest.ResourceManager#create(java.util.Map)
 *///from   w  w w  .j a  v  a  2 s. co  m
@Override
public URL create(Map<String, String> parameters) {
    checkResourceSet();

    try {
        URI requestUri = buildRequestUri(getResourceListURL(), parameters);

        ByteArrayEntity entity = new ByteArrayEntity(resource.asByteArray());
        entity.setContentType(resource.contentType().getMimeType());

        return executor.execute(Request.Post(requestUri).body(entity))
                .handleResponse(new ResponseHandler<URL>() {

                    /**
                     * @see org.apache.http.client.ResponseHandler#handleResponse(org.apache.http.HttpResponse)
                     */
                    @Override
                    public URL handleResponse(HttpResponse response)
                            throws ClientProtocolException, IOException {
                        StatusLine statusLine = response.getStatusLine();
                        if (statusLine.getStatusCode() >= 300) {
                            throw new HttpResponseException(statusLine.getStatusCode(),
                                    statusLine.getReasonPhrase());
                        }
                        if (statusLine.getStatusCode() == 201) {
                            Header locationHeader = response.getFirstHeader("Location");
                            if (locationHeader != null) {
                                return new URL(locationHeader.getValue());
                            }
                        }
                        return null;
                    }
                });
    } catch (Exception e) {
        throw new ResourceException(e);
    }
}

From source file:eu.fusepool.p3.webid.proxy.ProxyServlet.java

/**
 * The service method from HttpServlet, performs handling of all
 * HTTP-requests independent of their method. Requests and responses within
 * the method can be distinguished by belonging to the "frontend" (i.e. the
 * client connecting to the proxy) or the "backend" (the server being
 * contacted on behalf of the client)//from   w w  w  .j  ava  2s .c  o m
 *
 * @param frontendRequest Request coming in from the client
 * @param frontendResponse Response being returned to the client
 * @throws ServletException
 * @throws IOException
 */
@Override
protected void service(final HttpServletRequest frontendRequest, final HttpServletResponse frontendResponse)
        throws ServletException, IOException {
    log(LogService.LOG_INFO,
            "Proxying request: " + frontendRequest.getRemoteAddr() + ":" + frontendRequest.getRemotePort()
                    + " (" + frontendRequest.getHeader("Host") + ") " + frontendRequest.getMethod() + " "
                    + frontendRequest.getRequestURI());

    if (targetBaseUri == null) {
        // FIXME return status page
        return;
    }

    //////////////////// Setup backend request
    final HttpEntityEnclosingRequestBase backendRequest = new HttpEntityEnclosingRequestBase() {
        @Override
        public String getMethod() {
            return frontendRequest.getMethod();
        }
    };
    try {
        backendRequest.setURI(new URL(targetBaseUri + frontendRequest.getRequestURI()).toURI());
    } catch (URISyntaxException ex) {
        throw new IOException(ex);
    }

    //////////////////// Copy headers to backend request
    final Enumeration<String> frontendHeaderNames = frontendRequest.getHeaderNames();
    while (frontendHeaderNames.hasMoreElements()) {
        final String headerName = frontendHeaderNames.nextElement();
        final Enumeration<String> headerValues = frontendRequest.getHeaders(headerName);
        while (headerValues.hasMoreElements()) {
            final String headerValue = headerValues.nextElement();
            if (!headerName.equalsIgnoreCase("Content-Length")) {
                backendRequest.setHeader(headerName, headerValue);
            }
        }
    }

    //////////////////// Copy Entity - if any
    final byte[] inEntityBytes = IOUtils.toByteArray(frontendRequest.getInputStream());
    if (inEntityBytes.length > 0) {
        backendRequest.setEntity(new ByteArrayEntity(inEntityBytes));
    }

    //////////////////// Execute request to backend
    try (CloseableHttpResponse backendResponse = httpclient.execute(backendRequest)) {
        frontendResponse.setStatus(backendResponse.getStatusLine().getStatusCode());

        // Copy back headers
        final Header[] backendHeaders = backendResponse.getAllHeaders();
        final Set<String> backendHeaderNames = new HashSet<>(backendHeaders.length);
        for (Header header : backendHeaders) {
            if (backendHeaderNames.add(header.getName())) {
                frontendResponse.setHeader(header.getName(), header.getValue());
            } else {
                frontendResponse.addHeader(header.getName(), header.getValue());
            }
        }

        final ServletOutputStream outStream = frontendResponse.getOutputStream();

        // Copy back entity
        final HttpEntity entity = backendResponse.getEntity();
        if (entity != null) {
            try (InputStream inStream = entity.getContent()) {
                IOUtils.copy(inStream, outStream);
            }
        }
        outStream.flush();
    }
}

From source file:com.intel.cosbench.client.swift.SwiftClient.java

public void storeObject(String container, String object, byte[] data) throws IOException, SwiftException {
    SwiftResponse response = null;//from   w w w.j av  a  2 s  .  c o  m
    try {
        method = HttpClientUtil.makeHttpPut(getObjectPath(container, object));
        method.setHeader(X_AUTH_TOKEN, authToken);
        ByteArrayEntity entity = new ByteArrayEntity(data);
        entity.setChunked(false);
        entity.setContentType("application/octet-stream");
        ((HttpPut) method).setEntity(entity);
        response = new SwiftResponse(client.execute(method));
        if (response.getStatusCode() == SC_CREATED)
            return;
        if (response.getStatusCode() == SC_ACCEPTED)
            return;
        if (response.getStatusCode() == SC_NOT_FOUND)
            throw new SwiftFileNotFoundException("container not found: " + container,
                    response.getResponseHeaders(), response.getStatusLine());
        throw new SwiftException("unexpected return from server", response.getResponseHeaders(),
                response.getStatusLine());
    } finally {
        if (response != null)
            response.consumeResposeBody();
    }
}

From source file:com.nominanuda.web.http.HttpCoreHelper.java

private void fillMessageHeadersAndContent(HttpMessage msg, InputStream is) throws IOException, HttpException {
    CharArrayBuffer lineBuf = null;/*from w  ww.  j ava 2  s .  c  om*/
    long cl = 0;
    Header ct = null;
    Header ce = null;
    while ((lineBuf = readLine(is)).length() > 0) {
        Header h = lineParser.parseHeader(lineBuf);
        String hn = h.getName();
        if (HDR_CONTENT_LENGTH.equalsIgnoreCase(hn)) {
            cl = Long.valueOf(h.getValue());
        } else if (HDR_CONTENT_TYPE.equalsIgnoreCase(hn)) {
            ct = h;
        } else if (HDR_CONTENT_ENCODING.equalsIgnoreCase(hn)) {
            ce = h;
        } else {
            msg.addHeader(h);
        }
    }
    if (cl > 0) {
        byte[] payload = IO.readAndClose(is);
        Check.runtime.assertTrue(cl == payload.length);
        ByteArrayEntity bae = new ByteArrayEntity(payload);
        if (ct != null) {
            bae.setContentType(ct);
        }
        if (ce != null) {
            bae.setContentEncoding(ce);
        }
        setEntity(msg, bae);
    }
}

From source file:utils.TestUtils.java

public static String httpPost(String url, String data) throws Exception {
    CloseableHttpResponse resp = null;/*from  ww w . ja va2s. c om*/
    try {
        HttpPost post = new HttpPost(url);
        post.setEntity(new ByteArrayEntity(data.getBytes("UTF-8")));
        resp = HTTP.execute(post);
        return EntityUtils.toString(resp.getEntity(), "UTF-8");
    } finally {
        closeQuietly(resp);
    }
}