Example usage for org.apache.http.protocol HTTP CONTENT_ENCODING

List of usage examples for org.apache.http.protocol HTTP CONTENT_ENCODING

Introduction

In this page you can find the example usage for org.apache.http.protocol HTTP CONTENT_ENCODING.

Prototype

String CONTENT_ENCODING

To view the source code for org.apache.http.protocol HTTP CONTENT_ENCODING.

Click Source Link

Usage

From source file:riddimon.android.asianetautologin.HttpUtils.java

private HttpResponse execute(HttpMethod method, String url, Map<String, String> paramz,
        List<BasicHeader> headers) {
    if (!(method.equals(HttpMethod.GET) || method.equals(HttpMethod.DELETE) || method.equals(HttpMethod.PUT)
            || method.equals(HttpMethod.POST) || method.equals(HttpMethod.HEAD)) || TextUtils.isEmpty(url)) {
        logger.error("Invalid request : {} | {}", method.name(), url);
        return null;
    }//from  ww w.jav a2s  . c o m
    logger.debug("HTTP {} : {}", method.name(), url);
    String query = paramz == null ? null : getEncodedParameters(paramz);
    logger.trace("Query String : {}", query);
    HttpResponse httpResponse = null;
    try {
        HttpUriRequest req = null;
        switch (method) {
        case GET:
        case HEAD:
        case DELETE:
            url = paramz != null && paramz.size() > 0 ? url + "?" + query : url;
            if (method.equals(HttpMethod.GET)) {
                req = new HttpGet(url);
            } else if (method.equals(HttpMethod.DELETE)) {
                req = new HttpDelete(url);
            } else if (method.equals(HttpMethod.HEAD)) {
                req = new HttpHead(url);
            }
            break;
        case POST:
        case PUT:
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            if (paramz != null) {
                for (Entry<String, String> entry : paramz.entrySet()) {
                    params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
            }
            UrlEncodedFormEntity entity = paramz == null ? null : new UrlEncodedFormEntity(params);
            //               HttpEntity entity = TextUtils.isEmpty(query) ? null
            //                     : new StringEntity(query);
            BasicHeader header = new BasicHeader(HTTP.CONTENT_ENCODING, "application/x-www-form-urlencoded");
            if (method.equals(HttpMethod.PUT)) {
                HttpPut putr = new HttpPut(url);
                if (entity != null) {
                    putr.setHeader(header);
                    putr.setEntity(entity);
                    req = putr;
                }
            } else if (method.equals(HttpMethod.POST)) {
                HttpPost postr = new HttpPost(url);
                if (entity != null) {
                    postr.setHeader(header);
                    if (headers != null) {
                        for (BasicHeader h : headers) {
                            postr.addHeader(h);
                        }
                    }
                    postr.setEntity(entity);
                    req = postr;
                }
            }
        }
        httpResponse = HttpManager.execute(req, debug, version);
    } catch (IOException e1) {
        e1.printStackTrace();
        logger.error("HTTP request failed : {}", e1);
    }
    return httpResponse;
}

From source file:com.dh.perfectoffer.event.framework.net.network.NetworkConnectionImpl.java

/**
 * Call the webservice using the given parameters to construct the request
 * and return the result./*from ww w. j a  va2  s.co  m*/
 * 
 * @param context
 *            The context to use for this operation. Used to generate the
 *            user agent if needed.
 * @param urlValue
 *            The webservice URL.
 * @param method
 *            The request method to use.
 * @param parameterList
 *            The parameters to add to the request.
 * @param headerMap
 *            The headers to add to the request.
 * @param isGzipEnabled
 *            Whether the request will use gzip compression if available on
 *            the server.
 * @param userAgent
 *            The user agent to set in the request. If null, a default
 *            Android one will be created.
 * @param postText
 *            The POSTDATA text to add in the request.
 * @param credentials
 *            The credentials to use for authentication.
 * @param isSslValidationEnabled
 *            Whether the request will validate the SSL certificates.
 * @return The result of the webservice call.
 */
public static ConnectionResult execute(Context context, String urlValue, Method method,
        ArrayList<BasicNameValuePair> parameterList, HashMap<String, String> headerMap, boolean isGzipEnabled,
        String userAgent, String postText, UsernamePasswordCredentials credentials,
        boolean isSslValidationEnabled, String contentType, List<byte[]> fileByteDates,
        List<String> fileMimeTypes, int httpErrorResCodeFilte, boolean isMulFiles) throws ConnectionException {
    HttpURLConnection connection = null;
    try {
        // Prepare the request information
        if (userAgent == null) {
            userAgent = UserAgentUtils.get(context);
        }
        if (headerMap == null) {
            headerMap = new HashMap<String, String>();
        }
        headerMap.put(HTTP.USER_AGENT, userAgent);
        if (isGzipEnabled) {
            headerMap.put(ACCEPT_ENCODING_HEADER, "gzip");
        }
        headerMap.put(ACCEPT_CHARSET_HEADER, UTF8_CHARSET);
        if (credentials != null) {
            headerMap.put(AUTHORIZATION_HEADER, createAuthenticationHeader(credentials));
        }

        StringBuilder paramBuilder = new StringBuilder();
        if (parameterList != null && !parameterList.isEmpty()) {
            for (int i = 0, size = parameterList.size(); i < size; i++) {
                BasicNameValuePair parameter = parameterList.get(i);
                String name = parameter.getName();
                String value = parameter.getValue();
                if (TextUtils.isEmpty(name)) {
                    // Empty parameter name. Check the next one.
                    continue;
                }
                if (value == null) {
                    value = "";
                }
                paramBuilder.append(URLEncoder.encode(name, UTF8_CHARSET));
                paramBuilder.append("=");
                paramBuilder.append(URLEncoder.encode(value, UTF8_CHARSET));
                paramBuilder.append("&");
            }
        }

        // ?
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        // Create the connection object
        URL url = null;
        String outputText = null;
        switch (method) {
        case GET:
        case DELETE:
            String fullUrlValue = urlValue;
            if (paramBuilder.length() > 0) {
                fullUrlValue += "?" + paramBuilder.toString();
            }
            url = new URL(fullUrlValue);
            connection = HttpUrlConnectionHelper.openUrlConnection(url);
            break;
        case PUT:
        case POST:
            url = new URL(urlValue);
            connection = HttpUrlConnectionHelper.openUrlConnection(url);
            connection.setDoOutput(true);

            if (paramBuilder.length() > 0 && NetworkConnection.CT_DEFALUT.equals(contentType)) { // form
                // ?
                // headerMap.put(HTTP.CONTENT_TYPE,
                // "application/x-www-form-urlencoded");
                outputText = paramBuilder.toString();
                headerMap.put(HTTP.CONTENT_TYPE, contentType);
                headerMap.put(HTTP.CONTENT_LEN, String.valueOf(outputText.getBytes().length));
            } else if (postText != null && (NetworkConnection.CT_JSON.equals(contentType)
                    || NetworkConnection.CT_XML.equals(contentType))) { // body
                // ?
                // headerMap.put(HTTP.CONTENT_TYPE, "application/json");
                // //add ?json???
                headerMap.put(HTTP.CONTENT_TYPE, contentType); // add
                // ?json???
                headerMap.put(HTTP.CONTENT_LEN, String.valueOf(postText.getBytes().length));
                outputText = postText;
                // Log.e("newtewewerew",
                // "1111application/json------------------outputText222222:::"+outputText+"-------method::"+method+"----paramBuilder.length() :"+paramBuilder.length()+"----postText:"+postText
                // );
            } else if (NetworkConnection.CT_MULTIPART.equals(contentType)) { // 
                String[] Array = urlValue.split("/");
                /*Boolean isFiles = false;
                if (Array[Array.length - 1].equals("clientRemarkPic")) {
                   isFiles = true;
                }*/
                if (null == fileByteDates || fileByteDates.size() <= 0) {
                    throw new ConnectionException("file formdata no bytes data",
                            NetworkConnection.EXCEPTION_CODE_FORMDATA_NOBYTEDATE);
                }
                headerMap.put(HTTP.CONTENT_TYPE, contentType + ";boundary=" + BOUNDARY);
                String bulidFormText = bulidFormText(parameterList);
                bos.write(bulidFormText.getBytes());
                for (int i = 0; i < fileByteDates.size(); i++) {
                    long currentTimeMillis = System.currentTimeMillis();
                    StringBuffer sb = new StringBuffer("");
                    sb.append(PREFIX).append(BOUNDARY).append(LINEND);
                    // sb.append("Content-Type:application/octet-stream" +
                    // LINEND);
                    // sb.append("Content-Disposition: form-data; name=\""+nextInt+"\"; filename=\""+nextInt+".png\"").append(LINEND);;
                    if (isMulFiles)
                        sb.append("Content-Disposition: form-data; name=\"files\";filename=\"pic"
                                + currentTimeMillis + ".png\"").append(LINEND);
                    else
                        sb.append("Content-Disposition: form-data; name=\"file\";filename=\"pic"
                                + currentTimeMillis + ".png\"").append(LINEND);
                    // sb.append("Content-Type:image/png" + LINEND);
                    sb.append("Content-Type:" + fileMimeTypes.get(i) + LINEND);
                    // sb.append("Content-Type:image/png" + LINEND);
                    sb.append(LINEND);
                    bos.write(sb.toString().getBytes());
                    bos.write(fileByteDates.get(i));
                    bos.write(LINEND.getBytes());
                }
                byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
                bos.write(end_data);
                bos.flush();
                headerMap.put(HTTP.CONTENT_LEN, bos.size() + "");
            }
            // L.e("newtewewerew",
            // "2222------------------outputText222222:::"+outputText+"-------method::"+method+"----paramBuilder.length() :"+paramBuilder.length()+"----postText:"+postText
            // );
            break;
        }

        // Set the request method
        connection.setRequestMethod(method.toString());

        // If it's an HTTPS request and the SSL Validation is disabled
        if (url.getProtocol().equals("https") && !isSslValidationEnabled) {
            HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
            httpsConnection.setSSLSocketFactory(getAllHostsValidSocketFactory());
            httpsConnection.setHostnameVerifier(getAllHostsValidVerifier());
        }

        // Add the headers
        if (!headerMap.isEmpty()) {
            for (Entry<String, String> header : headerMap.entrySet()) {
                connection.addRequestProperty(header.getKey(), header.getValue());
            }
        }

        // Set the connection and read timeout
        connection.setConnectTimeout(OPERATION_TIMEOUT);
        connection.setReadTimeout(OPERATION_TIMEOUT);
        // Set the outputStream content for POST and PUT requests
        if ((method == Method.POST || method == Method.PUT)) {
            OutputStream output = null;
            try {
                if (NetworkConnection.CT_MULTIPART.equals(contentType)) {
                    output = connection.getOutputStream();
                    output.write(bos.toByteArray());
                } else {
                    if (null != outputText) {
                        L.e("newtewewerew", method + "------------------outputText:::" + outputText);
                        output = connection.getOutputStream();
                        output.write(outputText.getBytes());
                    }
                }

            } finally {
                if (output != null) {
                    try {
                        output.close();
                    } catch (IOException e) {
                        // Already catching the first IOException so nothing
                        // to do here.
                    }
                }
            }
        }

        // Log the request
        if (L.canLog(Log.DEBUG)) {
            L.d(TAG, "Request url: " + urlValue);
            L.d(TAG, "Method: " + method.toString());

            if (parameterList != null && !parameterList.isEmpty()) {
                L.d(TAG, "Parameters:");
                for (int i = 0, size = parameterList.size(); i < size; i++) {
                    BasicNameValuePair parameter = parameterList.get(i);
                    String message = "- \"" + parameter.getName() + "\" = \"" + parameter.getValue() + "\"";
                    L.d(TAG, message);
                }
                L.d(TAG, "Parameters String: \"" + paramBuilder.toString() + "\"");
            }

            if (postText != null) {
                L.d(TAG, "Post data: " + postText);
            }

            if (headerMap != null && !headerMap.isEmpty()) {
                L.d(TAG, "Headers:");
                for (Entry<String, String> header : headerMap.entrySet()) {
                    L.d(TAG, "- " + header.getKey() + " = " + header.getValue());
                }
            }
        }

        String contentEncoding = connection.getHeaderField(HTTP.CONTENT_ENCODING);

        int responseCode = connection.getResponseCode();
        boolean isGzip = contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip");
        L.d(TAG, "Response code: " + responseCode);

        if (responseCode == HttpStatus.SC_MOVED_PERMANENTLY) {
            String redirectionUrl = connection.getHeaderField(LOCATION_HEADER);
            throw new ConnectionException("New location : " + redirectionUrl, redirectionUrl);
        }

        InputStream errorStream = connection.getErrorStream();
        if (errorStream != null) {
            String error = convertStreamToString(errorStream, isGzip);
            // L.e("responseCode:"+responseCode+" httpErrorResCodeFilte:"+httpErrorResCodeFilte+" responseCode==httpErrorResCodeFilte:"+(responseCode==httpErrorResCodeFilte));
            if (responseCode == httpErrorResCodeFilte) { // 400???...
                logResBodyAndHeader(connection, error);
                return new ConnectionResult(connection.getHeaderFields(), error, responseCode);
            } else {
                throw new ConnectionException(error, responseCode);
            }
        }

        String body = convertStreamToString(connection.getInputStream(), isGzip);

        // ?? ?
        if (null != body && body.contains("\r")) {
            body = body.replace("\r", "");
        }

        if (null != body && body.contains("\n")) {
            body = body.replace("\n", "");
        }

        logResBodyAndHeader(connection, body);

        return new ConnectionResult(connection.getHeaderFields(), body, responseCode);
    } catch (IOException e) {
        L.e(TAG, "IOException", e);
        throw new ConnectionException(e);
    } catch (KeyManagementException e) {
        L.e(TAG, "KeyManagementException", e);
        throw new ConnectionException(e);
    } catch (NoSuchAlgorithmException e) {
        L.e(TAG, "NoSuchAlgorithmException", e);
        throw new ConnectionException(e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:com.mirth.connect.connectors.http.HttpReceiver.java

private void sendResponse(Request baseRequest, HttpServletResponse servletResponse,
        DispatchResult dispatchResult) throws Exception {
    ContentType contentType = ContentType
            .parse(replaceValues(connectorProperties.getResponseContentType(), dispatchResult));
    if (!connectorProperties.isResponseDataTypeBinary() && contentType.getCharset() == null) {
        /*//from w w  w .j av  a2 s  .c  om
         * If text mode is used and a specific charset isn't already defined, use the one from
         * the connector properties. We can't use ContentType.withCharset here because it
         * doesn't preserve other parameters, like boundary definitions
         */
        contentType = ContentType.parse(contentType.toString() + "; charset="
                + CharsetUtils.getEncoding(connectorProperties.getCharset()));
    }
    servletResponse.setContentType(contentType.toString());

    // set the response headers
    for (Entry<String, List<String>> entry : connectorProperties.getResponseHeaders().entrySet()) {
        for (String headerValue : entry.getValue()) {
            servletResponse.addHeader(entry.getKey(), replaceValues(headerValue, dispatchResult));
        }
    }

    // set the status code
    int statusCode = NumberUtils
            .toInt(replaceValues(connectorProperties.getResponseStatusCode(), dispatchResult), -1);

    /*
     * set the response body and status code (if we choose a response from the drop-down)
     */
    if (dispatchResult != null && dispatchResult.getSelectedResponse() != null) {
        dispatchResult.setAttemptedResponse(true);

        Response selectedResponse = dispatchResult.getSelectedResponse();
        Status newMessageStatus = selectedResponse.getStatus();

        /*
         * If the status code is custom, use the entered/replaced string If is is not a
         * variable, use the status of the destination's response (success = 200, failure = 500)
         * Otherwise, return 200
         */
        if (statusCode != -1) {
            servletResponse.setStatus(statusCode);
        } else if (newMessageStatus != null && newMessageStatus.equals(Status.ERROR)) {
            servletResponse.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        } else {
            servletResponse.setStatus(HttpStatus.SC_OK);
        }

        String message = selectedResponse.getMessage();

        if (message != null) {
            OutputStream responseOutputStream = servletResponse.getOutputStream();
            byte[] responseBytes;
            if (connectorProperties.isResponseDataTypeBinary()) {
                responseBytes = Base64Util.decodeBase64(message.getBytes("US-ASCII"));
            } else {
                responseBytes = message.getBytes(CharsetUtils.getEncoding(connectorProperties.getCharset()));
            }

            // If the client accepts GZIP compression, compress the content
            boolean gzipResponse = false;
            for (Enumeration<String> en = baseRequest.getHeaders("Accept-Encoding"); en.hasMoreElements();) {
                String acceptEncoding = en.nextElement();

                if (acceptEncoding != null && acceptEncoding.contains("gzip")) {
                    gzipResponse = true;
                    break;
                }
            }

            if (gzipResponse) {
                servletResponse.setHeader(HTTP.CONTENT_ENCODING, "gzip");
                GZIPOutputStream gzipOutputStream = new GZIPOutputStream(responseOutputStream);
                gzipOutputStream.write(responseBytes);
                gzipOutputStream.finish();
            } else {
                responseOutputStream.write(responseBytes);
            }

            // TODO include full HTTP payload in sentResponse
        }
    } else {
        /*
         * If the status code is custom, use the entered/replaced string Otherwise, return 200
         */
        if (statusCode != -1) {
            servletResponse.setStatus(statusCode);
        } else {
            servletResponse.setStatus(HttpStatus.SC_OK);
        }
    }
}

From source file:com.mirth.connect.connectors.http.HttpDispatcher.java

private HttpRequestBase buildHttpRequest(URI hostURI, HttpDispatcherProperties httpDispatcherProperties,
        ConnectorMessage connectorMessage, File tempFile, ContentType contentType, Charset charset)
        throws Exception {
    String method = httpDispatcherProperties.getMethod();
    boolean isMultipart = httpDispatcherProperties.isMultipart();
    Map<String, List<String>> headers = httpDispatcherProperties.getHeaders();
    Map<String, List<String>> parameters = httpDispatcherProperties.getParameters();

    Object content = null;//from  w w w.  ja v a2 s  . com
    if (httpDispatcherProperties.isDataTypeBinary()) {
        content = getAttachmentHandlerProvider().reAttachMessage(httpDispatcherProperties.getContent(),
                connectorMessage, null, true);
    } else {
        content = getAttachmentHandlerProvider().reAttachMessage(httpDispatcherProperties.getContent(),
                connectorMessage);

        // If text mode is used and a specific charset isn't already defined, use the one from the connector properties
        if (contentType.getCharset() == null) {
            contentType = HttpMessageConverter.setCharset(contentType, charset);
        }
    }

    // populate the query parameters
    List<NameValuePair> queryParameters = new ArrayList<NameValuePair>(parameters.size());

    for (Entry<String, List<String>> parameterEntry : parameters.entrySet()) {
        for (String value : parameterEntry.getValue()) {
            logger.debug("setting query parameter: [" + parameterEntry.getKey() + ", " + value + "]");
            queryParameters.add(new BasicNameValuePair(parameterEntry.getKey(), value));
        }
    }

    HttpRequestBase httpMethod = null;
    HttpEntity httpEntity = null;
    URIBuilder uriBuilder = new URIBuilder(hostURI);

    // create the method
    if ("GET".equalsIgnoreCase(method)) {
        setQueryString(uriBuilder, queryParameters);
        httpMethod = new HttpGet(uriBuilder.build());
    } else if ("POST".equalsIgnoreCase(method)) {
        if (isMultipart) {
            logger.debug("setting multipart file content");
            setQueryString(uriBuilder, queryParameters);
            httpMethod = new HttpPost(uriBuilder.build());

            if (content instanceof String) {
                FileUtils.writeStringToFile(tempFile, (String) content, contentType.getCharset(), false);
            } else {
                FileUtils.writeByteArrayToFile(tempFile, (byte[]) content, false);
            }

            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            multipartEntityBuilder.addPart(tempFile.getName(),
                    new FileBody(tempFile, contentType, tempFile.getName()));
            httpEntity = multipartEntityBuilder.build();
        } else if (StringUtils.startsWithIgnoreCase(contentType.getMimeType(),
                ContentType.APPLICATION_FORM_URLENCODED.getMimeType())) {
            httpMethod = new HttpPost(uriBuilder.build());
            httpEntity = new UrlEncodedFormEntity(queryParameters, contentType.getCharset());
        } else {
            setQueryString(uriBuilder, queryParameters);
            httpMethod = new HttpPost(uriBuilder.build());

            if (content instanceof String) {
                httpEntity = new StringEntity((String) content, contentType);
            } else {
                httpEntity = new ByteArrayEntity((byte[]) content);
            }
        }
    } else if ("PUT".equalsIgnoreCase(method)) {
        if (StringUtils.startsWithIgnoreCase(contentType.getMimeType(),
                ContentType.APPLICATION_FORM_URLENCODED.getMimeType())) {
            httpMethod = new HttpPut(uriBuilder.build());
            httpEntity = new UrlEncodedFormEntity(queryParameters, contentType.getCharset());
        } else {
            setQueryString(uriBuilder, queryParameters);
            httpMethod = new HttpPut(uriBuilder.build());

            if (content instanceof String) {
                httpEntity = new StringEntity((String) content, contentType);
            } else {
                httpEntity = new ByteArrayEntity((byte[]) content);
            }
        }
    } else if ("DELETE".equalsIgnoreCase(method)) {
        setQueryString(uriBuilder, queryParameters);
        httpMethod = new HttpDelete(uriBuilder.build());
    }

    if (httpMethod instanceof HttpEntityEnclosingRequestBase) {
        // Compress the request entity if necessary
        List<String> contentEncodingList = (List<String>) new CaseInsensitiveMap(headers)
                .get(HTTP.CONTENT_ENCODING);
        if (CollectionUtils.isNotEmpty(contentEncodingList)) {
            for (String contentEncoding : contentEncodingList) {
                if (contentEncoding != null && (contentEncoding.toLowerCase().equals("gzip")
                        || contentEncoding.toLowerCase().equals("x-gzip"))) {
                    httpEntity = new GzipCompressingEntity(httpEntity);
                    break;
                }
            }
        }

        ((HttpEntityEnclosingRequestBase) httpMethod).setEntity(httpEntity);
    }

    // set the headers
    for (Entry<String, List<String>> headerEntry : headers.entrySet()) {
        for (String value : headerEntry.getValue()) {
            logger.debug("setting method header: [" + headerEntry.getKey() + ", " + value + "]");
            httpMethod.addHeader(headerEntry.getKey(), value);
        }
    }

    // Only set the Content-Type for entity-enclosing methods, but not if multipart is used
    if (("POST".equalsIgnoreCase(method) || "PUT".equalsIgnoreCase(method)) && !isMultipart) {
        httpMethod.setHeader(HTTP.CONTENT_TYPE, contentType.toString());
    }

    return httpMethod;
}

From source file:com.mirth.connect.connectors.http.HttpReceiver.java

private HttpRequestMessage createRequestMessage(Request request, boolean ignorePayload)
        throws IOException, MessagingException {
    HttpRequestMessage requestMessage = new HttpRequestMessage();
    requestMessage.setMethod(request.getMethod());
    requestMessage.setHeaders(HttpMessageConverter.convertFieldEnumerationToMap(request));
    requestMessage.setParameters(extractParameters(request));

    ContentType contentType;//from ww  w  .  j  a v  a  2s .co  m
    try {
        contentType = ContentType.parse(request.getContentType());
    } catch (RuntimeException e) {
        contentType = ContentType.TEXT_PLAIN;
    }
    requestMessage.setContentType(contentType);

    requestMessage.setRemoteAddress(StringUtils.trimToEmpty(request.getRemoteAddr()));
    requestMessage.setQueryString(StringUtils.trimToEmpty(request.getQueryString()));
    requestMessage.setRequestUrl(StringUtils.trimToEmpty(getRequestURL(request)));
    requestMessage.setContextPath(StringUtils.trimToEmpty(new URL(requestMessage.getRequestUrl()).getPath()));

    if (!ignorePayload) {
        InputStream requestInputStream = request.getInputStream();
        // If a security handler already consumed the entity, get it from the request attribute instead
        try {
            byte[] entity = (byte[]) request.getAttribute(EntityProvider.ATTRIBUTE_NAME);
            if (entity != null) {
                requestInputStream = new ByteArrayInputStream(entity);
            }
        } catch (Exception e) {
        }

        // If the request is GZIP encoded, uncompress the content
        List<String> contentEncodingList = requestMessage.getCaseInsensitiveHeaders()
                .get(HTTP.CONTENT_ENCODING);
        if (CollectionUtils.isNotEmpty(contentEncodingList)) {
            for (String contentEncoding : contentEncodingList) {
                if (contentEncoding != null && (contentEncoding.equalsIgnoreCase("gzip")
                        || contentEncoding.equalsIgnoreCase("x-gzip"))) {
                    requestInputStream = new GZIPInputStream(requestInputStream);
                    break;
                }
            }
        }

        /*
         * First parse out the body of the HTTP request. Depending on the connector settings,
         * this could end up being a string encoded with the request charset, a byte array
         * representing the raw request payload, or a MimeMultipart object.
         */

        // Only parse multipart if XML Body is selected and Parse Multipart is enabled
        if (connectorProperties.isXmlBody() && connectorProperties.isParseMultipart()
                && ServletFileUpload.isMultipartContent(request)) {
            requestMessage.setContent(
                    new MimeMultipart(new ByteArrayDataSource(requestInputStream, contentType.toString())));
        } else if (isBinaryContentType(contentType)) {
            requestMessage.setContent(IOUtils.toByteArray(requestInputStream));
        } else {
            requestMessage.setContent(IOUtils.toString(requestInputStream,
                    HttpMessageConverter.getDefaultHttpCharset(request.getCharacterEncoding())));
        }
    }

    return requestMessage;
}

From source file:com.hp.mqm.client.MqmRestClientImpl.java

private long postTestResult(ByteArrayEntity entity, boolean skipErrors) {
    HttpPost request = new HttpPost(createSharedSpaceInternalApiUri(URI_TEST_RESULT_PUSH, skipErrors));
    request.setHeader(HTTP.CONTENT_ENCODING, CONTENT_ENCODING_GZIP);
    request.setEntity(entity);//from   w w  w.  ja  v  a2s .  c  o m
    HttpResponse response = null;
    try {
        response = execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_SERVICE_UNAVAILABLE) {
            throw new TemporarilyUnavailableException("Service not available");
        }
        if (statusCode != HttpStatus.SC_ACCEPTED) {
            throw createRequestException("Test result post failed", response);
        }
        String json = IOUtils.toString(response.getEntity().getContent());
        JSONObject jsonObject = JSONObject.fromObject(json);
        return jsonObject.getLong("id");
    } catch (java.io.FileNotFoundException e) {
        throw new FileNotFoundException("Cannot find test result file.", e);
    } catch (IOException e) {
        throw new RequestErrorException("Cannot post test results to MQM.", e);
    } finally {
        HttpClientUtils.closeQuietly(response);
    }
}

From source file:com.newrelic.agent.android.harvest.HarvestConnection.java

public HttpPost createPost(String str, String str2) {
    String str3 = (str2.length() <= AccessibilityNodeInfoCompat.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY
            || DISABLE_COMPRESSION_FOR_DEBUGGING.booleanValue()) ? HTTP.IDENTITY_CODING : "deflate";
    HttpPost httpPost = new HttpPost(str);
    httpPost.addHeader(HTTP.CONTENT_TYPE, AbstractSpiCall.ACCEPT_JSON_VALUE);
    httpPost.addHeader(HTTP.CONTENT_ENCODING, str3);
    httpPost.addHeader(HTTP.USER_AGENT, System.getProperty("http.agent"));
    if (this.applicationToken == null) {
        this.log.error("Cannot create POST without an Application Token.");
        return null;
    }/*from   ww w .j a  v  a2  s.c om*/
    httpPost.addHeader(APPLICATION_TOKEN_HEADER, this.applicationToken);
    if (this.serverTimestamp != 0) {
        httpPost.addHeader(CONNECT_TIME_HEADER, Long.valueOf(this.serverTimestamp).toString());
    }
    if ("deflate".equals(str3)) {
        httpPost.setEntity(new ByteArrayEntity(deflate(str2)));
    } else {
        try {
            httpPost.setEntity(new StringEntity(str2, "utf-8"));
        } catch (Throwable e) {
            this.log.error("UTF-8 is unsupported");
            throw new IllegalArgumentException(e);
        }
    }
    return httpPost;
}

From source file:org.apache.synapse.transport.nhttp.util.ResponseAcceptEncodingProcessor.java

public static void process(final MessageContext response, final MessageContext request) {

    if (response == null) {
        throw new IllegalArgumentException("Response Message Context cannot be null");
    }/*from   w w  w  . j a v a 2s  .  c  om*/

    if (request == null) {
        throw new IllegalArgumentException("Request Message context cannot be null");
    }

    Object o = request.getProperty(MessageContext.TRANSPORT_HEADERS);
    if (o != null && o instanceof Map) {
        Map headers = (Map) o;

        String encode = (String) headers.get(ACCEPT_ENCODING);
        if (encode != null) {

            //If message  contains 'Accept-Encoding' header and  if it's value is 'qzip'
            if (GZIP_CODEC.equals(encode)) {

                Object obj = response.getProperty(MessageContext.TRANSPORT_HEADERS);
                Map responseHeaders;

                if (obj != null && obj instanceof Map) {
                    responseHeaders = (Map) obj;
                } else {
                    responseHeaders = new HashMap();
                    response.setProperty(MessageContext.TRANSPORT_HEADERS, responseHeaders);
                }

                if (log.isDebugEnabled()) {
                    log.debug("Sets the 'Content-Encoding' header as ' " + GZIP_CODEC + " '");
                }

                responseHeaders.put(HTTP.CONTENT_ENCODING, GZIP_CODEC);

            }
            //if there are any type for 'Accept-Encoding' , those should go here
        }
    }
}