Example usage for org.apache.http.entity ByteArrayEntity setContentEncoding

List of usage examples for org.apache.http.entity ByteArrayEntity setContentEncoding

Introduction

In this page you can find the example usage for org.apache.http.entity ByteArrayEntity setContentEncoding.

Prototype

public void setContentEncoding(Header header) 

Source Link

Usage

From source file:com.subgraph.vega.internal.http.proxy.ProxyRequestHandler.java

private HttpEntity copyEntity(HttpEntity entity) {
    try {/*  w w w . j ava2s  .co m*/
        if (entity == null) {
            return null;
        }
        final ByteArrayEntity newEntity = new ByteArrayEntity(EntityUtils.toByteArray(entity));
        newEntity.setContentEncoding(entity.getContentEncoding());
        newEntity.setContentType(entity.getContentType());
        return newEntity;
    } catch (IOException e) {
        return null;
    }
}

From source file:com.subgraph.vega.ui.httpviewer.entity.HttpEntityBinaryViewer.java

private HttpEntity createEntity(byte[] content, String contentType, String contentEncoding) {
    final ByteArrayEntity entity = new ByteArrayEntity(content);
    if (contentType != null && !contentType.isEmpty()) {
        entity.setContentType(contentType);
    }//w  ww . ja  v  a2 s .co  m
    if (contentEncoding != null && !contentEncoding.isEmpty()) {
        entity.setContentEncoding(contentEncoding);
    }
    return entity;
}

From source file:org.callimachusproject.server.chain.TransactionHandler.java

private ByteArrayEntity copyEntity(HttpEntity entity, int length) throws IOException {
    InputStream in = entity.getContent();
    try {//from   w  w w.j  av  a 2 s  . co m
        if (length < 0) {
            length = ONE_PACKET;
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream(length);
        ChannelUtil.transfer(in, baos);
        ByteArrayEntity bae = new ByteArrayEntity(baos.toByteArray());
        bae.setContentEncoding(entity.getContentEncoding());
        bae.setContentType(entity.getContentType());
        return bae;
    } finally {
        in.close();
    }
}

From source file:com.subgraph.vega.internal.http.requests.EngineHttpResponse.java

@Override
public boolean lockResponseEntity() {
    final HttpEntity entity = rawResponse.getEntity();
    if (entity == null)
        return false;
    try {//  ww w. j a va2 s .  c o  m
        final ByteArrayEntity newEntity = new ByteArrayEntity(EntityUtils.toByteArray(entity));
        newEntity.setContentType(entity.getContentType());
        newEntity.setContentEncoding(entity.getContentEncoding());
        rawResponse.setEntity(newEntity);
        EntityUtils.consume(entity);
        return true;
    } catch (IOException e) {
        logger.warning("Error loading entity for " + getRequestUri().toString() + " : " + e.getMessage());
        return false;
    }
}

From source file:com.chatsdk.kenai.jbosh.ApacheHTTPResponse.java

/**
 * Create and send a new request to the upstream connection manager,
 * providing deferred access to the results to be returned.
 *
 * @param client client instance to use when sending the request
 * @param cfg client configuration// www . j ava 2  s.c  om
 * @param params connection manager parameters from the session creation
 *  response, or {@code null} if the session has not yet been established
 * @param request body of the client request
 */
ApacheHTTPResponse(final HttpClient client, final BOSHClientConfig cfg, final CMSessionParams params,
        final AbstractBody request) {
    super();
    this.client = client;
    this.context = new BasicHttpContext();
    this.post = new HttpPost(cfg.getURI().toString());
    this.sent = false;

    try {
        String xml = request.toXML();
        byte[] data = xml.getBytes(CHARSET);

        String encoding = null;
        if (cfg.isCompressionEnabled() && params != null) {
            AttrAccept accept = params.getAccept();
            if (accept != null) {
                if (accept.isAccepted(ZLIBCodec.getID())) {
                    encoding = ZLIBCodec.getID();
                    data = ZLIBCodec.encode(data);
                } else if (accept.isAccepted(GZIPCodec.getID())) {
                    encoding = GZIPCodec.getID();
                    data = GZIPCodec.encode(data);
                }
            }
        }

        ByteArrayEntity entity = new ByteArrayEntity(data);
        entity.setContentType(CONTENT_TYPE);
        if (encoding != null) {
            entity.setContentEncoding(encoding);
        }
        post.setEntity(entity);
        if (cfg.isCompressionEnabled()) {
            post.setHeader(ACCEPT_ENCODING, ACCEPT_ENCODING_VAL);
        }
    } catch (Exception e) {
        toThrow = new BOSHException("Could not generate request", e);
    }
}

From source file:org.mule.module.http.functional.listener.HttpListenerAttachmentsTestCase.java

private HttpEntity createHttpEntity(boolean useChunkedMode) throws IOException {
    HttpEntity multipartEntity = getMultipartEntity(true);
    if (useChunkedMode) {
        //The only way to send multipart + chunked is putting the multipart content in an output stream entity.
        ByteArrayOutputStream multipartOutput = new ByteArrayOutputStream();
        multipartEntity.writeTo(multipartOutput);
        multipartOutput.flush();//from  ww  w  .  j av a  2  s .c  o  m
        ByteArrayEntity byteArrayEntity = new ByteArrayEntity(multipartOutput.toByteArray());
        multipartOutput.close();

        byteArrayEntity.setChunked(true);
        byteArrayEntity.setContentEncoding(multipartEntity.getContentEncoding());
        byteArrayEntity.setContentType(multipartEntity.getContentType());
        return byteArrayEntity;
    } else {
        return multipartEntity;
    }
}

From source file:org.mobicents.applications.ussd.examples.http.push.HTTPPush.java

/**
 * @param serialized/*w w  w .  j  a  va  2s  .c om*/
 * @return
 */
protected HttpResponse send(byte[] serialized) throws Exception {
    HttpUriRequest post = new HttpPost(this.targetURI);
    if (!(post instanceof HttpEntityEnclosingRequestBase)) {
        throw new IOException();
    }
    addStatusEntry("Sending:\n" + new String(serialized));
    ByteArrayEntity entity = new ByteArrayEntity(serialized);
    entity.setContentType("text/xml");
    entity.setContentEncoding(Charset.defaultCharset().toString());
    ((HttpEntityEnclosingRequestBase) post).setEntity(entity);

    return this.httpClient.execute(post, this.context);
}

From source file:br.com.anteros.android.synchronism.communication.HttpConnectionClient.java

public MobileResponse sendReceiveData(MobileRequest mobileRequest) {
    sessionId = HttpConnectionSession.getInstance().getSessionId();

    add(mobileRequest.getFormattedHeader(), mobileRequest.getFormatedActions());
    MobileResponse mobileResponse = new MobileResponse();
    try {/*from  w ww  .  j a  v  a 2s  .c o m*/
        if (this.getSendData() != null) {
            for (MobileSendDataListener listener : this.getSendData().getListeners())
                listener.onWaitServer();
        }

        if (this.getSendData() != null) {
            for (MobileSendDataListener listener : this.getSendData().getListeners())
                listener.onStatusConnectionServer("Conectando Servidor...");
        }

        /*
         * Define url e estabelece conexo
         */

        HttpPost httpPost = new HttpPost(url);

        HttpParams httpParameters = new BasicHttpParams();
        // Set the timeout in milliseconds until a connection is
        // established.
        // The default value is zero, that means the timeout is not used.
        HttpConnectionParams.setConnectionTimeout(httpParameters, TIMEOUT_CONNECTION);
        // Set the default socket timeout (SO_TIMEOUT)
        // in milliseconds which is the timeout for waiting for data.
        HttpConnectionParams.setSoTimeout(httpParameters, TIMEOUT_SOCKET);

        if (httpClient == null)
            httpClient = new DefaultHttpClient(httpParameters);

        //

        /*
         * Setar o cookie da sesso
         */
        if ((sessionId != null) && (!"".equals(sessionId))) {
            httpPost.setHeader("Cookie", "JSESSIONID=" + sessionId);
        }
        httpPost.setHeader("User-Agent", "Android");
        httpPost.setHeader("Accept-Encoding", "gzip");

        if (this.getSendData() != null) {
            for (MobileSendDataListener listener : this.getSendData().getListeners())
                listener.onStatusConnectionServer("Enviando requisio...");
        }

        //
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream out = new DataOutputStream(baos);
        //

        /*
         * Escrever no output
         */
        out.writeInt(numOption);
        String aux[];
        for (int i = 0; i < opPOST.size(); i++) {
            aux = (String[]) opPOST.get(i);

            out.writeUTF(aux[0]);

            byte[] b = aux[1].getBytes();
            out.writeInt(b.length);
            out.write(b);

            aux = null;
        }
        out.flush();

        ByteArrayEntity entity = new ByteArrayEntity(baos.toByteArray());
        entity.setContentEncoding("UTF-8");
        httpPost.setEntity(entity);
        httpPost.addHeader("Connection", "Keep-Alive");
        httpPost.addHeader("Keep-Alive", "timeout=120000");

        out.close();
        //

        if (this.getSendData() != null) {
            for (MobileSendDataListener listener : this.getSendData().getListeners())
                listener.onStatusConnectionServer("Recebendo dados...");
        }

        if (this.getSendData() != null) {
            for (MobileSendDataListener listener : this.getSendData().getListeners())
                listener.onDebugMessage("Recebendo dados conexo");
        }

        /*
         * Aguardar resposta
         */
        HttpResponse httpResponse = httpClient.execute(httpPost);
        List result = null;
        StatusLine statusLine = httpResponse.getStatusLine();
        int code = statusLine.getStatusCode();
        if (code != 200) {
            String msg = "Erro RECEBENDO resposta do Servidor " + url + " - Cdigo do Erro HTTP " + code + "-"
                    + statusLine.getReasonPhrase();
            mobileResponse.setStatus(msg);
        } else {
            if (this.getSendData() != null) {
                for (MobileSendDataListener listener : this.getSendData().getListeners())
                    listener.onStatusConnectionServer("Resposta OK !");
            }

            /*
             * Ler cookie
             */
            String tmpSessionId = null;

            for (Cookie c : httpClient.getCookieStore().getCookies()) {
                if ("JSESSIONID".equals(c.getName())) {
                    tmpSessionId = c.getValue();
                }
            }

            if (tmpSessionId != null) {
                sessionId = tmpSessionId;
                HttpConnectionSession.getInstance().setSessionId(sessionId);
            }
            //

            if (this.getSendData() != null) {
                for (MobileSendDataListener listener : this.getSendData().getListeners())
                    listener.onStatusConnectionServer("Lendo dados...");
            }

            /*
             * Le os dados
             */
            HttpEntity entityResponse = httpResponse.getEntity();
            InputStream in = AndroidHttpClient.getUngzippedContent(entityResponse);

            BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));

            String content = null;

            content = reader.readLine();
            String line = null;
            while ((line = reader.readLine()) != null) {
                content += line;
            }
            line = "";

            reader.close();
            reader = null;
            in.close();
            in = null;
            entityResponse.consumeContent();
            entityResponse = null;
            //

            StringTokenizer messagePart = new StringTokenizer(content, "#");
            content = null;

            if (this.getSendData() != null) {
                for (MobileSendDataListener listener : this.getSendData().getListeners())
                    listener.onDebugMessage("RECEBEU dados conexo");
            }

            if (this.getSendData() != null) {
                for (MobileSendDataListener listener : this.getSendData().getListeners())
                    listener.onStatusConnectionServer("Processando resposta... ");
            }

            if (this.getSendData() != null) {
                for (MobileSendDataListener listener : this.getSendData().getListeners())
                    listener.onDebugMessage("Converteu string dados conexo");
            }

            while (messagePart.hasMoreTokens()) {
                String resultData = messagePart.nextToken();
                resultData = resultData.substring(resultData.indexOf("*") + 1, resultData.length());
                if (result == null)
                    result = formatData(resultData);
                else
                    result.addAll(formatData(resultData));
            }
            messagePart = null;
        }

        if (result != null) {
            mobileResponse.setFormattedParameters(result);
            result.clear();
            result = null;
        }

        if (this.getSendData() != null) {
            for (MobileSendDataListener listener : this.getSendData().getListeners())
                listener.onEndServer();
        }

    } catch (SocketTimeoutException exTimeout) {
        exTimeout.printStackTrace();
        wrapException(mobileResponse, "No foi possvel CONECTAR ao Servidor " + url
                + ". Verifique sua conexo e se o servidor est em funcionamento.");
    } catch (Exception e) {
        e.printStackTrace();
        if ((e.getMessage() + "").contains("unreachable"))
            wrapException(mobileResponse,
                    "Voc est sem acesso a internet. Verifique sua conexo. No foi possvel conectar ao servidor  "
                            + url);
        else
            wrapException(mobileResponse,
                    "No foi possivel CONECTAR ao Servidor " + url + " " + e.getMessage());
    }
    return mobileResponse;
}

From source file:com.rackspacecloud.blueflood.inputs.handlers.HttpHandlerIntegrationTest.java

@Test
public void testCompressedRequests() throws Exception {

    URIBuilder builder = getMetricsURIBuilder().setPath("/v2.0/acTEST/ingest");

    HttpPost post = new HttpPost(builder.build());
    String content = generateJSONMetricsData();
    ByteArrayOutputStream baos = new ByteArrayOutputStream(content.length());
    GZIPOutputStream gzipOut = new GZIPOutputStream(baos);
    gzipOut.write(content.getBytes());//  ww w  . ja  v a  2s. c o  m
    gzipOut.close();
    ByteArrayEntity entity = new ByteArrayEntity(baos.toByteArray());
    //Setting the content encoding to gzip
    entity.setContentEncoding("gzip");
    baos.close();
    post.setEntity(entity);
    HttpResponse response = client.execute(post);

    try {
        assertEquals(200, response.getStatusLine().getStatusCode());
    } finally {
        EntityUtils.consume(response.getEntity()); // Releases connection apparently
    }
}

From source file:org.coronastreet.gpxconverter.GarminForm.java

public void upload() {
    httpClient = HttpClientBuilder.create().build();
    localContext = new BasicHttpContext();
    cookieStore = new BasicCookieStore();
    localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
    //httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

    if (doLogin()) {
        try {//w  w  w  .  java  2s .co  m
            HttpGet get = new HttpGet("http://connect.garmin.com/transfer/upload#");
            HttpResponse formResponse = httpClient.execute(get, localContext);
            HttpEntity formEntity = formResponse.getEntity();
            EntityUtils.consume(formEntity);

            HttpPost request = new HttpPost(
                    "http://connect.garmin.com/proxy/upload-service-1.1/json/upload/.tcx");
            request.setHeader("Referer",
                    "http://connect.garmin.com/api/upload/widget/manualUpload.faces?uploadServiceVersion=1.1");
            request.setHeader("Accept", "text/html, application/xhtml+xml, */*");
            MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
            entity.addPart("data",
                    new InputStreamBody(document2InputStream(outDoc), "application/octet-stream", "temp.tcx"));

            // Need to do this bit because without it you can't disable chunked encoding
            ByteArrayOutputStream bArrOS = new ByteArrayOutputStream();
            entity.writeTo(bArrOS);
            bArrOS.flush();
            ByteArrayEntity bArrEntity = new ByteArrayEntity(bArrOS.toByteArray());
            bArrOS.close();

            bArrEntity.setChunked(false);
            bArrEntity.setContentEncoding(entity.getContentEncoding());
            bArrEntity.setContentType(entity.getContentType());

            request.setEntity(bArrEntity);

            HttpResponse response = httpClient.execute(request, localContext);

            if (response.getStatusLine().getStatusCode() != 200) {
                log("Failed to Upload");
                HttpEntity en = response.getEntity();
                if (en != null) {
                    String output = EntityUtils.toString(en);
                    log(output);
                }
            } else {
                HttpEntity ent = response.getEntity();
                if (ent != null) {
                    String output = EntityUtils.toString(ent);
                    output = "[" + output + "]"; //OMG Garmin Sucks at JSON.....
                    JSONObject uploadResponse = new JSONArray(output).getJSONObject(0);
                    JSONObject importResult = uploadResponse.getJSONObject("detailedImportResult");
                    try {
                        int uploadID = importResult.getInt("uploadId");
                        log("Success! UploadID is " + uploadID);
                    } catch (Exception e) {
                        JSONArray failures = (JSONArray) importResult.get("failures");
                        JSONObject failure = (JSONObject) failures.get(0);
                        JSONArray errorMessages = failure.getJSONArray("messages");
                        JSONObject errorMessage = errorMessages.getJSONObject(0);
                        String content = errorMessage.getString("content");
                        log("Upload Failed! Error: " + content);
                    }
                }
            }
            httpClient.close();
        } catch (Exception ex) {
            log("Exception? " + ex.getMessage());
            ex.printStackTrace();
            // handle exception here
        }
    } else {
        log("Failed to upload!");
    }
}