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

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

Introduction

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

Prototype

String CONTENT_TYPE

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

Click Source Link

Usage

From source file:AdminAssetCreateTest.java

public void routeCreateAsset() {
    mParametersSimple.put(PARAM_NAME, TEST_ASSET_NAME());
    mParametersSimple.put(PARAM_META, getPayload("/adminAssetCreateMeta.json").toString());

    FakeRequest request = new FakeRequest(getMethod(), getRouteAddress());
    request = request.withHeader(TestConfig.KEY_APPCODE, TestConfig.VALUE_APPCODE);
    request = request.withHeader(TestConfig.KEY_AUTH, TestConfig.AUTH_ADMIN_ENC);
    request = request.withHeader(HTTP.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED);
    request = request.withFormUrlEncodedBody(mParametersSimple);
    Result result = routeAndCall(request);
    assertRoute(result, "testRouteCreateSimpleAsset", Status.CREATED, null, true);
}

From source file:com.spoiledmilk.ibikecph.util.HttpUtils.java

public static JsonNode putToServer(String urlString, JSONObject objectToPost) {
    JsonNode ret = null;//  ww  w.  j  av a  2  s  . co  m
    LOG.d("PUT api request, url = " + urlString);
    HttpParams myParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(myParams, CONNECTON_TIMEOUT);
    HttpConnectionParams.setSoTimeout(myParams, CONNECTON_TIMEOUT);
    HttpClient httpclient = new DefaultHttpClient(myParams);
    httpclient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, Config.USER_AGENT);
    HttpPut httput = null;
    URL url = null;
    try {
        url = new URL(urlString);
        httput = new HttpPut(url.toString());
        httput.setHeader("Content-type", "application/json");
        httput.setHeader("Accept", ACCEPT);
        httput.setHeader("LANGUAGE_CODE", IbikeApplication.getLanguageString());
        StringEntity se = new StringEntity(objectToPost.toString(), HTTP.UTF_8);
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        httput.setEntity(se);
        HttpResponse response = httpclient.execute(httput);
        String serverResponse = EntityUtils.toString(response.getEntity());
        LOG.d("API response = " + serverResponse);
        ret = Util.stringToJsonNode(serverResponse);
    } catch (Exception e) {
        if (e != null && e.getLocalizedMessage() != null) {
            LOG.e(e.getLocalizedMessage());
        }
    }
    return ret;
}

From source file:com.intellij.tasks.impl.httpclient.TaskResponseUtil.java

public static void prettyFormatResponseToLog(@Nonnull Logger logger, @Nonnull HttpMethod response) {
    if (logger.isDebugEnabled() && response.hasBeenUsed()) {
        try {// ww w . j  av  a  2s  .c  o m
            String content = TaskResponseUtil.getResponseContentAsString(response);
            org.apache.commons.httpclient.Header header = response.getRequestHeader(HTTP.CONTENT_TYPE);
            String contentType = header == null ? "text/plain"
                    : header.getElements()[0].getName().toLowerCase(Locale.ENGLISH);
            if (contentType.contains("xml")) {
                TaskUtil.prettyFormatXmlToLog(logger, content);
            } else if (contentType.contains("json")) {
                TaskUtil.prettyFormatJsonToLog(logger, content);
            } else {
                logger.debug(content);
            }
        } catch (IOException e) {
            logger.error(e);
        }
    }
}

From source file:org.apache.synapse.transport.nhttp.Axis2HttpRequest.java

/**
 * Create and return a new HttpPost request to the destination EPR
 *
 * @return the HttpRequest to be sent out
 * @throws IOException in error retrieving the <code>HttpRequest</code>
 *//* ww w.  ja v a2s.  com*/
public HttpRequest getRequest() throws IOException, HttpException {
    String httpMethod = (String) msgContext.getProperty(Constants.Configuration.HTTP_METHOD);
    if (httpMethod == null) {
        httpMethod = "POST";
    }
    endpointURLPrefix = (String) msgContext.getProperty(NhttpConstants.ENDPOINT_PREFIX);

    boolean forceHTTP10 = msgContext.isPropertyTrue(NhttpConstants.FORCE_HTTP_1_0);
    HttpVersion httpver = forceHTTP10 ? HttpVersion.HTTP_1_0 : HttpVersion.HTTP_1_1;

    HttpRequest httpRequest;

    try {
        if ("POST".equals(httpMethod) || "PUT".equals(httpMethod) || "PATCH".equals(httpMethod)) {

            URI uri = rewriteRequestURI(new URI(epr.getAddress()));
            BasicHttpEntityEnclosingRequest requestWithEntity = new BasicHttpEntityEnclosingRequest(httpMethod,
                    uri.toASCIIString(), httpver);

            BasicHttpEntity entity = new BasicHttpEntity();

            if (forceHTTP10) {
                setStreamAsTempData(entity);
            } else {
                entity.setChunked(chunked);
                if (!chunked) {
                    setStreamAsTempData(entity);
                }
            }
            requestWithEntity.setEntity(entity);
            requestWithEntity.setHeader(HTTP.CONTENT_TYPE,
                    messageFormatter.getContentType(msgContext, format, msgContext.getSoapAction()));
            httpRequest = requestWithEntity;

        } else if ("GET".equals(httpMethod) || "DELETE".equals(httpMethod)) {

            URL url = messageFormatter.getTargetAddress(msgContext, format, new URL(epr.getAddress()));

            URI uri = rewriteRequestURI(url.toURI());
            httpRequest = new BasicHttpRequest(httpMethod, uri.toASCIIString(), httpver);
            /*GETs and DELETEs do not need Content-Type headers because they do not have payloads*/
            //httpRequest.setHeader(HTTP.CONTENT_TYPE, messageFormatter.getContentType(
            //        msgContext, format, msgContext.getSoapAction()));

        } else {
            URI uri = rewriteRequestURI(new URI(epr.getAddress()));
            httpRequest = new BasicHttpRequest(httpMethod, uri.toASCIIString(), httpver);
        }

    } catch (URISyntaxException ex) {
        throw new HttpException(ex.getMessage(), ex);
    }

    // set any transport headers
    Object o = msgContext.getProperty(MessageContext.TRANSPORT_HEADERS);
    if (o != null && o instanceof Map) {
        Map headers = (Map) o;
        for (Object header : headers.keySet()) {
            Object value = headers.get(header);
            if (header instanceof String && value != null && value instanceof String) {
                if (!HTTPConstants.HEADER_HOST.equalsIgnoreCase((String) header)) {
                    httpRequest.setHeader((String) header, (String) value);

                    String excessProp = NhttpConstants.EXCESS_TRANSPORT_HEADERS;

                    Map map = (Map) msgContext.getProperty(excessProp);
                    if (map != null && map.get(header) != null) {
                        log.debug("Number of excess values for " + header + " header is : "
                                + ((Collection) (map.get(header))).size());

                        for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
                            String key = (String) iterator.next();

                            for (String excessVal : (Collection<String>) map.get(key)) {
                                httpRequest.addHeader((String) header, (String) excessVal);
                            }

                        }
                    }

                } else {
                    if (msgContext.getProperty(NhttpConstants.REQUEST_HOST_HEADER) != null) {
                        httpRequest.setHeader((String) header,
                                (String) msgContext.getProperty(NhttpConstants.REQUEST_HOST_HEADER));
                    }
                }

            }
        }
    }

    // if the message is SOAP 11 (for which a SOAPAction is *required*), and
    // the msg context has a SOAPAction or a WSA-Action (give pref to SOAPAction)
    // use that over any transport header that may be available
    String soapAction = msgContext.getSoapAction();
    if (soapAction == null) {
        soapAction = msgContext.getWSAAction();
    }
    if (soapAction == null) {
        msgContext.getAxisOperation().getInputAction();
    }

    if (msgContext.isSOAP11() && soapAction != null && soapAction.length() >= 0) {
        Header existingHeader = httpRequest.getFirstHeader(HTTPConstants.HEADER_SOAP_ACTION);
        if (existingHeader != null) {
            httpRequest.removeHeader(existingHeader);
        }
        httpRequest.setHeader(HTTPConstants.HEADER_SOAP_ACTION,
                messageFormatter.formatSOAPAction(msgContext, null, soapAction));
    }

    if (NHttpConfiguration.getInstance().isKeepAliveDisabled()
            || msgContext.isPropertyTrue(NhttpConstants.NO_KEEPALIVE)) {
        httpRequest.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);
    }

    return httpRequest;
}

From source file:org.jsnap.http.base.HttpServlet.java

protected void doService(org.apache.http.HttpRequest request, org.apache.http.HttpResponse response)
        throws HttpException, IOException {
    // Client might keep the executing thread blocked for very long unless this header is added.
    response.addHeader(new Header(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE));
    // Create a wrapped request object.
    String uri, data;/*from w  w w. j av  a2 s . c  o  m*/
    String method = request.getRequestLine().getMethod();
    if (method.equals(HttpGet.METHOD_NAME)) {
        BasicHttpRequest get = (BasicHttpRequest) request;
        data = get.getRequestLine().getUri();
        int ix = data.indexOf('?');
        uri = (ix < 0 ? data : data.substring(0, ix));
        data = (ix < 0 ? "" : data.substring(ix + 1));
    } else if (method.equals(HttpPost.METHOD_NAME)) {
        BasicHttpEntityEnclosingRequest post = (BasicHttpEntityEnclosingRequest) request;
        HttpEntity postedEntity = post.getEntity();
        uri = post.getRequestLine().getUri();
        data = EntityUtils.toString(postedEntity);
    } else {
        response.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED);
        response.setHeader(new Header(HTTP.CONTENT_LEN, "0"));
        return;
    }
    String cookieLine = "";
    if (request.containsHeader(COOKIE)) {
        Header[] cookies = request.getHeaders(COOKIE);
        for (Header cookie : cookies) {
            if (cookieLine.length() > 0)
                cookieLine += "; ";
            cookieLine += cookie.getValue();
        }
    }
    HttpRequest req = new HttpRequest(uri, underlying, data, cookieLine);
    // Create a wrapped response object.
    ByteArrayOutputStream out = new ByteArrayOutputStream(BUFFER_SIZE);
    HttpResponse resp = new HttpResponse(out);
    // Do implementation specific processing.
    doServiceImpl(req, resp);
    out.flush(); // It's good practice to do this.
    // Do the actual writing to the actual response object.
    if (resp.redirectTo != null) {
        // Redirection is requested.
        resp.statusCode = HttpStatus.SC_MOVED_TEMPORARILY;
        response.setStatusCode(resp.statusCode);
        Header redirection = new Header(LOCATION, resp.redirectTo);
        response.setHeader(redirection);
        Logger.getLogger(HttpServlet.class).log(Level.DEBUG,
                "Status Code: " + Integer.toString(resp.statusCode));
        Logger.getLogger(HttpServlet.class).log(Level.DEBUG, redirection.toString());
    } else {
        // There will be a response entity.
        response.setStatusCode(resp.statusCode);
        HttpEntity entity;
        Header contentTypeHeader;
        boolean text = resp.contentType.startsWith(Formatter.TEXT);
        if (text) { // text/* ...
            entity = new StringEntity(out.toString(resp.characterSet), resp.characterSet);
            contentTypeHeader = new Header(HTTP.CONTENT_TYPE,
                    resp.contentType + HTTP.CHARSET_PARAM + resp.characterSet);
        } else { // application/octet-stream, image/* ...
            entity = new ByteArrayEntity(out.toByteArray());
            contentTypeHeader = new Header(HTTP.CONTENT_TYPE, resp.contentType);
        }
        boolean acceptsGzip = clientAcceptsGzip(request);
        long contentLength = entity.getContentLength();
        // If client accepts gzipped content, the implementing object requested that response
        // gets gzipped and size of the response exceeds implementing object's size threshold
        // response entity will be gzipped.
        boolean gzipped = false;
        if (acceptsGzip && resp.zipSize > 0 && contentLength >= resp.zipSize) {
            ByteArrayOutputStream zipped = new ByteArrayOutputStream(BUFFER_SIZE);
            GZIPOutputStream gzos = new GZIPOutputStream(zipped);
            entity.writeTo(gzos);
            gzos.close();
            entity = new ByteArrayEntity(zipped.toByteArray());
            contentLength = zipped.size();
            gzipped = true;
        }
        // This is where true writes are made.
        Header contentLengthHeader = new Header(HTTP.CONTENT_LEN, Long.toString(contentLength));
        Header contentEncodingHeader = null;
        response.setHeader(contentTypeHeader);
        response.setHeader(contentLengthHeader);
        if (gzipped) {
            contentEncodingHeader = new Header(CONTENT_ENCODING, Formatter.GZIP);
            response.setHeader(contentEncodingHeader);
        }
        response.setEntity(entity);
        // Log critical headers.
        Logger.getLogger(HttpServlet.class).log(Level.DEBUG,
                "Status Code: " + Integer.toString(resp.statusCode));
        Logger.getLogger(HttpServlet.class).log(Level.DEBUG, contentTypeHeader.toString());
        if (gzipped)
            Logger.getLogger(HttpServlet.class).log(Level.DEBUG, contentEncodingHeader.toString());
        Logger.getLogger(HttpServlet.class).log(Level.DEBUG, contentLengthHeader.toString());
    }
    // Log cookies.
    for (Cookie cookie : resp.cookies) {
        if (cookie.valid()) {
            Header h = new Header(SET_COOKIE, cookie.toString());
            response.addHeader(h);
            Logger.getLogger(HttpServlet.class).log(Level.DEBUG, h.toString());
        }
    }
}

From source file:anhttpclient.AnhttpclientTest.java

@Test
public void testFormParamsRequest() throws Exception {
    final Map<String, String> params = new HashMap<String, String>();
    params.put("email", "sss@ggg.com");
    params.put("space", "aaa bbb");
    params.put("russian", "");
    params.put("some_chars", "!@#$%^&*()_+|");

    server.addHandler("/formParams", new ByteArrayHandlerAdapter() {
        public byte[] getResponseAsByteArray(HttpRequestContext httpRequestContext) throws IOException {
            assertEquals("Form should be url-encoded", "application/x-www-form-urlencoded; charset=UTF-8",
                    httpRequestContext.getRequestHeaders().get(HTTP.CONTENT_TYPE).get(0));
            assertEquals(httpRequestContext.getRequestBody().length, Integer
                    .valueOf(httpRequestContext.getRequestHeaders().get("Content-length").get(0)).intValue());

            try {
                String postParams = new String(httpRequestContext.getRequestBody());
                String[] paramValuePairs = postParams.split("\\&");
                for (String paramValuePair : paramValuePairs) {
                    String[] paramValueArray = paramValuePair.split("\\=");
                    String param = paramValueArray[0];
                    String value = java.net.URLDecoder.decode(paramValueArray[1], "UTF-8");
                    assertEquals("incorrect param value", value, params.get(param));
                }//  ww w. ja  v  a  2s  . c  om
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

            return "OK".getBytes();
        }
    });

    for (Map.Entry<RequestMethod, Class<? extends WebRequest>> entry : allRequests.entrySet()) {
        if (entry.getKey().equals(RequestMethod.POST) || entry.getKey().equals(RequestMethod.PUT)) {
            EntityEnclosingWebRequest req = (EntityEnclosingWebRequest) entry.getValue().newInstance();
            req.setUrl(server.getBaseUrl() + "/formParams");
            req.addFormParams(params);

            wb.getResponse(req);
        }
    }
}

From source file:com.android.internal.http.multipart.MultipartEntity.java

@Override
public Header getContentType() {
    StringBuffer buffer = new StringBuffer(MULTIPART_FORM_CONTENT_TYPE);
    buffer.append("; boundary=");
    buffer.append(EncodingUtils.getAsciiString(getMultipartBoundary()));
    return new BasicHeader(HTTP.CONTENT_TYPE, buffer.toString());

}

From source file:local.apache.MultipartEntity.java

@Override
public Header getContentType() {
    final StringBuffer buffer = new StringBuffer(MULTIPART_FORM_CONTENT_TYPE);
    buffer.append("; boundary=");
    buffer.append(EncodingUtils.getAsciiString(getMultipartBoundary()));
    return new BasicHeader(HTTP.CONTENT_TYPE, buffer.toString());

}

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 w w  w .j  a v a2 s.  c  om
 * 
 * @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:dk.kk.ibikecphlib.util.HttpUtils.java

public static JsonNode putToServer(String urlString, JSONObject objectToPost) {
    JsonNode ret = null;//from w ww . j  a v  a 2  s .com
    LOG.d("PUT api request, url = " + urlString);
    HttpParams myParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(myParams, CONNECTON_TIMEOUT);
    HttpConnectionParams.setSoTimeout(myParams, CONNECTON_TIMEOUT);
    HttpClient httpclient = new DefaultHttpClient(myParams);
    httpclient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, Config.USER_AGENT);
    HttpPut httput = null;
    URL url = null;
    try {
        url = new URL(urlString);
        httput = new HttpPut(url.toString());
        httput.setHeader("Content-type", "application/json");
        httput.setHeader("Accept", ACCEPT);
        httput.setHeader("LANGUAGE_CODE", IBikeApplication.getLanguageString());
        StringEntity se = new StringEntity(objectToPost.toString(), HTTP.UTF_8);
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        httput.setEntity(se);
        HttpResponse response = httpclient.execute(httput);
        String serverResponse = EntityUtils.toString(response.getEntity());
        LOG.d("API response = " + serverResponse);
        ret = Util.stringToJsonNode(serverResponse);
    } catch (Exception e) {
        if (e != null && e.getLocalizedMessage() != null) {
            LOG.e(e.getLocalizedMessage());
        }
    }
    return ret;
}