Example usage for java.net HttpURLConnection getErrorStream

List of usage examples for java.net HttpURLConnection getErrorStream

Introduction

In this page you can find the example usage for java.net HttpURLConnection getErrorStream.

Prototype

public InputStream getErrorStream() 

Source Link

Document

Returns the error stream if the connection failed but the server sent useful data nonetheless.

Usage

From source file:com.cr_wd.android.network.HttpClient.java

/**
 * Performs a HTTP GET/POST Request//from w  w w.  j a  va2  s.  co  m
 * 
 * @return id of the request
 */
protected int doRequest(final Method method, final String url, HttpHeaders headers, HttpParams params,
        final HttpHandler handler) {
    if (headers == null) {
        headers = new HttpHeaders();
    }
    if (params == null) {
        params = new HttpParams();
    }

    handler.client = this;

    final int requestId = incrementRequestId();

    class HandlerRunnable extends Handler implements Runnable {

        private final Method method;
        private String url;
        private final HttpHeaders headers;
        private final HttpParams params;
        private final HttpHandler handler;
        private HttpResponse response;

        private boolean canceled = false;
        private int retries = 0;

        protected HandlerRunnable(final Method method, final String url, final HttpHeaders headers,
                final HttpParams params, final HttpHandler handler) {
            this.method = method;
            this.url = url;
            this.headers = headers;
            this.params = params;
            this.handler = handler;
        }

        @Override
        public void run() {
            execute();
        }

        private void execute() {
            response = new HttpResponse(requestId, method, url);

            HttpURLConnection conn = null;
            try {
                /* append query string for GET requests */
                if (method == Method.GET) {
                    if (!params.urlParams.isEmpty()) {
                        url += ('?' + params.getParamString());
                    }
                }

                /* setup headers for POST requests */
                if (method == Method.POST) {
                    headers.addHeader("Accept-Charset", requestOptions.encoding);
                    if (params.hasMultipartParams()) {
                        final SimpleMultipart multipart = params.getMultipart();
                        headers.addHeader("Content-Type", multipart.getContentType());
                    } else {
                        headers.addHeader("Content-Type",
                                "application/x-www-form-urlencoded;charset=" + requestOptions.encoding);
                    }
                }

                if (canceled) {
                    postCancel();
                    return;
                }

                /* open and configure the connection */
                conn = (HttpURLConnection) new URL(url).openConnection();

                postStart();

                if (method == Method.GET) {
                    conn = (HttpURLConnection) new URL(url).openConnection();
                    conn.setRequestMethod("GET");
                } else if (method == Method.POST) {
                    conn.setRequestMethod("POST");
                    conn.setDoOutput(true);
                    conn.setDoInput(true);
                    conn.setUseCaches(false);
                }
                conn.setAllowUserInteraction(false);
                conn.setReadTimeout(requestOptions.readTimeout);
                conn.setConnectTimeout(requestOptions.connectTimeout);

                /* add headers to the connection */
                for (final Map.Entry<String, List<String>> entry : headers.getHeaders().entrySet()) {
                    for (final String value : entry.getValue()) {
                        conn.addRequestProperty(entry.getKey(), value);
                    }
                }

                if (canceled) {
                    try {
                        conn.disconnect();
                    } catch (final Exception e) {
                    }
                    postCancel();
                    return;
                }

                response.requestProperties = conn.getRequestProperties();

                /* do post */
                if (method == Method.POST) {
                    InputStream is;

                    if (params.hasMultipartParams()) {
                        is = params.getMultipart().getContent();
                    } else {
                        is = new ByteArrayInputStream(params.getParamString().getBytes());
                    }

                    final OutputStream os = conn.getOutputStream();

                    writeStream(os, is);
                } else {
                    conn.connect();
                }

                if (canceled) {
                    try {
                        conn.disconnect();
                    } catch (final Exception e) {
                    }
                    postCancel();
                    return;
                }

                response.contentEncoding = conn.getContentEncoding();
                response.contentLength = conn.getContentLength();
                response.contentType = conn.getContentType();
                response.date = conn.getDate();
                response.expiration = conn.getExpiration();
                response.headerFields = conn.getHeaderFields();
                response.ifModifiedSince = conn.getIfModifiedSince();
                response.lastModified = conn.getLastModified();
                response.responseCode = conn.getResponseCode();
                response.responseMessage = conn.getResponseMessage();

                /* do get */
                if (conn.getResponseCode() < 400) {
                    response.responseBody = readStream(conn.getInputStream());
                    postSuccess();
                } else {
                    response.responseBody = readStream(conn.getErrorStream());
                    response.throwable = new Exception(response.responseMessage);
                    postError();
                }

            } catch (final Exception e) {
                if (retries < requestOptions.maxRetries) {
                    retries++;
                    postRetry();
                    execute();
                } else {
                    response.responseBody = e.getMessage();
                    response.throwable = e;
                    postError();
                }
            } finally {
                if (conn != null) {
                    conn.disconnect();
                }
            }
        }

        private String readStream(final InputStream is) throws IOException {
            final BufferedInputStream bis = new BufferedInputStream(is);
            final ByteArrayBuffer baf = new ByteArrayBuffer(50);
            int read = 0;
            final byte[] buffer = new byte[8192];
            while (true) {
                if (canceled) {
                    break;
                }

                read = bis.read(buffer);
                if (read == -1) {
                    break;
                }
                baf.append(buffer, 0, read);
            }

            try {
                bis.close();
            } catch (final IOException e) {
            }

            try {
                is.close();
            } catch (final IOException e) {
            }

            return new String(baf.toByteArray());
        }

        private void writeStream(final OutputStream os, final InputStream is) throws IOException {
            final BufferedInputStream bis = new BufferedInputStream(is);
            int read = 0;
            final byte[] buffer = new byte[8192];
            while (true) {
                if (canceled) {
                    break;
                }

                read = bis.read(buffer);
                if (read == -1) {
                    break;
                }
                os.write(buffer, 0, read);
            }

            if (!canceled) {
                os.flush();
            }

            try {
                os.close();
            } catch (final IOException e) {
            }

            try {
                bis.close();
            } catch (final IOException e) {
            }

            try {
                is.close();
            } catch (final IOException e) {
            }
        }

        @Override
        public void handleMessage(final Message msg) {
            if (msg.what == HttpHandler.MESSAGE_CANCEL) {
                canceled = true;
            }
        }

        private void postSuccess() {
            postMessage(HttpHandler.MESSAGE_SUCCESS);
        }

        private void postError() {
            postMessage(HttpHandler.MESSAGE_ERROR);
        }

        private void postCancel() {
            postMessage(HttpHandler.MESSAGE_CANCEL);
        }

        private void postStart() {
            postMessage(HttpHandler.MESSAGE_START);
        }

        private void postRetry() {
            postMessage(HttpHandler.MESSAGE_RETRY);
        }

        private void postMessage(final int what) {
            final Message msg = handler.obtainMessage();
            msg.what = what;
            msg.arg1 = requestId;
            msg.obj = response;
            handler.sendMessage(msg);
        }
    }
    ;
    /* Create a new HandlerRunnable and start it */
    final HandlerRunnable hr = new HandlerRunnable(method, url, headers, params, handler);
    requests.put(requestId, new WeakReference<Handler>(hr));
    new Thread(hr).start();

    /* Return with the request id */
    return requestId;
}

From source file:it.govpay.core.utils.client.BasicClient.java

private byte[] send(boolean soap, String azione, JAXBElement<?> body, Object header, boolean isAzioneInUrl)
        throws ClientException {

    // Creazione Connessione
    int responseCode;
    HttpURLConnection connection = null;
    byte[] msg = null;
    GpContext ctx = GpThreadLocal.get();
    String urlString = url.toExternalForm();
    if (isAzioneInUrl) {
        if (!urlString.endsWith("/"))
            urlString = urlString.concat("/");
        try {//from ww  w  .j  a  va  2s  .  co m
            url = new URL(urlString.concat(azione));
        } catch (MalformedURLException e) {
            throw new ClientException("Url di connessione malformata: " + urlString.concat(azione), e);
        }
    }

    try {
        Message requestMsg = new Message();
        requestMsg.setType(MessageType.REQUEST_OUT);

        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        if (soap) {
            connection.setRequestProperty("SOAPAction", "\"" + azione + "\"");
            requestMsg.addHeader(new Property("SOAPAction", "\"" + azione + "\""));
        }
        requestMsg.setContentType("text/xml");
        connection.setRequestProperty("Content-Type", "text/xml");
        connection.setRequestMethod("POST");

        // Imposta Contesto SSL se attivo
        if (sslContext != null) {
            HttpsURLConnection httpsConn = (HttpsURLConnection) connection;
            httpsConn.setSSLSocketFactory(sslContext.getSocketFactory());
            HostNameVerifierDisabled disabilitato = new HostNameVerifierDisabled();
            httpsConn.setHostnameVerifier(disabilitato);
        }

        // Imposta l'autenticazione HTTP Basic se attiva
        if (ishttpBasicEnabled) {
            Base64 base = new Base64();
            String encoding = new String(base.encode((httpBasicUser + ":" + httpBasicPassword).getBytes()));
            connection.setRequestProperty("Authorization", "Basic " + encoding);
            requestMsg.addHeader(new Property("Authorization", "Basic " + encoding));
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        if (soap) {
            SOAPUtils.writeMessage(body, header, baos);
        } else {
            JaxbUtils.marshal(body, baos);
        }

        ctx.getIntegrationCtx().setMsg(baos.toByteArray());
        invokeOutHandlers();

        if (log.getLevel().isMoreSpecificThan(Level.TRACE)) {
            StringBuffer sb = new StringBuffer();
            for (String key : connection.getRequestProperties().keySet()) {
                sb.append("\n\t" + key + ": " + connection.getRequestProperties().get(key));
            }
            sb.append("\n" + new String(ctx.getIntegrationCtx().getMsg()));
            log.trace(sb.toString());
        }

        requestMsg.setContent(ctx.getIntegrationCtx().getMsg());

        ctx.getContext().getRequest().setOutDate(new Date());
        ctx.getContext().getRequest().setOutSize(Long.valueOf(ctx.getIntegrationCtx().getMsg().length));
        ctx.log(requestMsg);

        connection.getOutputStream().write(ctx.getIntegrationCtx().getMsg());

    } catch (Exception e) {
        throw new ClientException(e);
    }
    try {
        responseCode = connection.getResponseCode();
        ctx.getTransaction().getServer().setTransportCode(Integer.toString(responseCode));

    } catch (Exception e) {
        throw new ClientException(e);
    }

    Message responseMsg = new Message();
    responseMsg.setType(MessageType.RESPONSE_IN);

    for (String key : connection.getHeaderFields().keySet()) {
        if (connection.getHeaderFields().get(key) != null) {
            if (key == null)
                responseMsg
                        .addHeader(new Property("Status-line", connection.getHeaderFields().get(key).get(0)));
            else if (connection.getHeaderFields().get(key).size() == 1)
                responseMsg.addHeader(new Property(key, connection.getHeaderFields().get(key).get(0)));
            else
                responseMsg.addHeader(
                        new Property(key, ArrayUtils.toString(connection.getHeaderFields().get(key))));
        }
    }

    try {
        if (responseCode < 300) {
            try {
                if (connection.getInputStream() == null) {
                    return null;
                }
                msg = connection.getInputStream() != null ? IOUtils.toByteArray(connection.getInputStream())
                        : new byte[] {};
                if (msg.length > 0)
                    responseMsg.setContent(msg);
                return msg;
            } catch (Exception e) {
                throw new ClientException("Messaggio di risposta non valido", e);
            }
        } else {
            try {
                msg = connection.getErrorStream() != null ? IOUtils.toByteArray(connection.getErrorStream())
                        : new byte[] {};
                responseMsg.setContent(msg);
            } catch (IOException e) {
                msg = ("Impossibile serializzare l'ErrorStream della risposta: " + e).getBytes();
            } finally {
                log.warn("Errore nell'invocazione del Nodo dei Pagamenti [HTTP Response Code " + responseCode
                        + "]\nRisposta: " + new String(msg));
            }

            throw new ClientException("Ricevuto [HTTP " + responseCode + "]");
        }
    } finally {
        if (responseMsg != null) {
            ctx.getContext().getResponse().setInDate(new Date());
            ctx.getContext().getResponse().setInSize((long) responseMsg.getContent().length);
            ctx.log(responseMsg);
        }

        if (log.getLevel().isMoreSpecificThan(Level.TRACE) && connection != null
                && connection.getHeaderFields() != null) {
            StringBuffer sb = new StringBuffer();
            for (String key : connection.getHeaderFields().keySet()) {
                sb.append("\n\t" + key + ": " + connection.getHeaderField(key));
            }
            sb.append("\n" + new String(msg));
            log.trace(sb.toString());
        }
    }

}

From source file:com.google.code.linkedinapi.client.impl.BaseLinkedInApiClient.java

/**
 * @param apiUrl/*from   w  w  w  . j  a v a  2s.c  o  m*/
 * @param xmlContent
 * @param contentType
 * @param method
 * @param expected
 * @return
 */
protected void callApiMethod(String apiUrl, String xmlContent, String contentType, HttpMethod method,
        int expected) {
    try {
        LinkedInOAuthService oAuthService = LinkedInOAuthServiceFactory.getInstance()
                .createLinkedInOAuthService(apiConsumer.getConsumerKey(), apiConsumer.getConsumerSecret());

        if (accessToken.getOauth2Token() != null && !accessToken.getOauth2Token().isEmpty()) {
            // oauth2 token hack, this seemed like the easiest... place to do it
            if (apiUrl.contains("?")) {
                apiUrl = apiUrl + "&oauth2_access_token=" + accessToken.getOauth2Token();
            } else {
                apiUrl = apiUrl + "?oauth2_access_token=" + accessToken.getOauth2Token();
            }
        }

        if (OUTPUT_RESPONSE) {
            LOG.info("Calling LinkedIn URL: " + apiUrl);
            LOG.info("XML Content: " + xmlContent);
        }

        URL url = new URL(apiUrl);

        HttpURLConnection request = (HttpURLConnection) url.openConnection();

        if (ApplicationConstants.CONNECT_TIMEOUT > -1) {
            request.setConnectTimeout(ApplicationConstants.CONNECT_TIMEOUT);
        }

        if (ApplicationConstants.READ_TIMEOUT > -1) {
            request.setReadTimeout(ApplicationConstants.READ_TIMEOUT);
        }

        for (String headerName : requestHeaders.keySet()) {
            request.setRequestProperty(headerName, requestHeaders.get(headerName));
        }

        request.setRequestMethod(method.fieldName());
        request.setDoOutput(true);
        oAuthService.signRequestWithToken(request, accessToken);

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

        if (xmlContent != null) {
            PrintWriter out = new PrintWriter(
                    new OutputStreamWriter(request.getOutputStream(), UTF_8_CHAR_SET));

            out.print(xmlContent);
            out.flush();
            out.close();
        }

        request.connect();

        if (request.getResponseCode() != expected) {
            Error error = readResponse(Error.class, getWrappedInputStream(request.getErrorStream(),
                    GZIP_ENCODING.equalsIgnoreCase(request.getContentEncoding())));

            throw createLinkedInApiClientException(error);
        } else {
            //        return getWrappedInputStream(request.getInputStream(),
            //            GZIP_ENCODING.equalsIgnoreCase(request.getContentEncoding()));
            InputStream inputStream = getWrappedInputStream(request.getInputStream(),
                    GZIP_ENCODING.equalsIgnoreCase(request.getContentEncoding()));
            String response = convertStreamToString(inputStream);
            if (OUTPUT_RESPONSE) {
                LOG.info("Response: " + response);
            }
        }
    } catch (IOException e) {
        throw new LinkedInApiClientException(e);
    }
}

From source file:com.truebanana.http.HTTPRequest.java

/**
 * Executes this {@link HTTPRequest} asynchronously. To hook to events or listen to the server response, you must provide an {@link HTTPResponseListener} using {@link HTTPRequest#setHTTPResponseListener(HTTPResponseListener)}.
 *
 * @return This {@link HTTPRequest}/*from  w  ww  .jav a 2s .  c om*/
 */
public HTTPRequest executeAsync() {
    Async.executeAsync(new Runnable() {
        @Override
        public void run() {
            HttpURLConnection urlConnection = buildURLConnection();

            // Get request body now if there's a provider
            if (bodyProvider != null) {
                body = bodyProvider.getRequestBody();
            }

            // Update socket factory as needed
            if (urlConnection instanceof HttpsURLConnection) {
                HttpsURLConnection httpsURLConnection = (HttpsURLConnection) urlConnection;

                try {
                    httpsURLConnection.setSSLSocketFactory(new FlexibleSSLSocketFactory(trustStore,
                            trustStorePassword, keyStore, keyStorePassword, !verifySSL));
                } catch (GeneralSecurityException e) {
                    e.printStackTrace();
                    onRequestError(HTTPRequestError.SECURITY_EXCEPTION);
                    onRequestTerminated();
                    return; // Terminate now
                } catch (IOException e) {
                    e.printStackTrace();
                    onRequestError(HTTPRequestError.KEYSTORE_INVALID);
                    onRequestTerminated();
                    return; // Terminate now
                }

                if (!verifySSL) {
                    httpsURLConnection.setHostnameVerifier(new NoVerifyHostnameVerifier());
                    log("SSL Verification Disabled", "**********");
                }
            }

            log("Endpoint", urlConnection.getURL().toString());
            Iterator<Map.Entry<String, String>> iterator = headers.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, String> pair = (Map.Entry) iterator.next();
                urlConnection.addRequestProperty(pair.getKey(), pair.getValue());
                log("Request Header", pair.getKey() + ": " + pair.getValue());
            }
            if (multiPartContent != null) {
                log("Multipart Request Boundary", multiPartContent.getBoundary());
                int counter = 1;
                for (MultiPartContent.Part part : multiPartContent.getParts()) {
                    log("Request Body Part " + counter,
                            "Name: " + part.getName() + "; File Name: " + part.getFileName());

                    Iterator<Map.Entry<String, String>> it = part.getHeaders().entrySet().iterator();
                    while (it.hasNext()) {
                        Map.Entry<String, String> pair = (Map.Entry) it.next();
                        log("Request Body Part " + counter + " Header", pair.getKey() + ": " + pair.getValue());
                    }
                }
            } else {
                log("Request Body", body);
            }

            if (mockResponse == null) {
                // Trigger pre-execute since preparations are complete
                onPreExecute();

                // Write our request body
                try {
                    if (multiPartContent != null) {
                        multiPartContent.write(urlConnection.getOutputStream());
                    } else if (body != null) {
                        OutputStream os = urlConnection.getOutputStream();
                        OutputStreamWriter writer = new OutputStreamWriter(os);
                        writer.write(body);
                        writer.flush();
                        writer.close();
                        os.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    onRequestError(HTTPRequestError.OTHER);
                    onRequestTerminated();
                    return; // Terminate now
                }

                // Get the response
                InputStream content;
                try {
                    content = urlConnection.getInputStream();
                    onPostExecute();
                } catch (SocketTimeoutException e) { // Timeout
                    e.printStackTrace();
                    onPostExecute();
                    onRequestError(HTTPRequestError.TIMEOUT);
                    onRequestTerminated();
                    return; // Terminate now
                } catch (IOException e) { // All other exceptions
                    e.printStackTrace();
                    content = urlConnection.getErrorStream();
                    onPostExecute();
                }

                // Pre-process the response
                final HTTPResponse response = HTTPResponse.from(HTTPRequest.this, urlConnection, content);

                if (response.isConnectionError()) {
                    onRequestError(HTTPRequestError.OTHER);
                    onRequestTerminated();
                    return; // Terminate now
                }

                // Log response
                log("Response Message", response.getResponseMessage());
                log("Response Content", response.getStringContent());

                // Trigger request completed and return the response
                onRequestCompleted(response);

                // Terminate the connection
                urlConnection.disconnect();

                onRequestTerminated();
            } else {
                onPreExecute();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                onPostExecute();
                log("Response Message", mockResponse.getResponseMessage());
                log("Response Content", mockResponse.getStringContent());
                onRequestCompleted(mockResponse);
                urlConnection.disconnect();
                onRequestTerminated();
            }
        }
    });
    return this;
}

From source file:com.wso2telco.dep.mediator.RequestExecutor.java

/**
 * Make request./*from  ww  w.  j ava 2s.c  om*/
 *
 * @param operatorendpoint
 *            the operatorendpoint
 * @param url
 *            the url
 * @param requestStr
 *            the request str
 * @param auth
 *            the auth
 * @param messageContext
 *            the message context
 * @return the string
 */
public String makeRequest(OperatorEndpoint operatorendpoint, String url, String requestStr, boolean auth,
        MessageContext messageContext, boolean inclueHeaders) {

    //MO Callback
    boolean isMoCallBack = false;
    JSONObject jsonObject = null;
    try {
        jsonObject = new JSONObject(requestStr);
    } catch (JSONException error) {
        error.printStackTrace();
    }
    Iterator<String> keys = jsonObject.keys();
    if (keys.hasNext()) {
        String key = (String) keys.next();
        if (key.equals("inboundSMSMessageNotification") || key.equals("deliveryInfoNotification")) {
            isMoCallBack = true;
        }
    }

    try {// check for charge operation. if true append ESB url
        JSONObject jsonObj = new JSONObject(requestStr);
        String transactionOperationStatus = jsonObj.getJSONObject("amountTransaction")
                .getString("transactionOperationStatus");
        String status = "Charged";
        if (status.equals(transactionOperationStatus)) {
            url = modifyEndpoint(url, operatorendpoint.getOperator(), messageContext);
        }
    } catch (JSONException ignore) {
    }

    ICallresponse icallresponse = null;
    String retStr = "";
    int statusCode = 0;

    URL neturl;
    HttpURLConnection connection = null;

    try {
        // String Authtoken = AccessToken;
        // //FileUtil.getApplicationProperty("wow.api.bearer.token");

        // String encodeurl = URLEncoder.encode(url, "UTF-8");
        neturl = new URL(url);
        connection = (HttpURLConnection) neturl.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "application/json");
        //connection.setRequestProperty("charset", "utf-8");
        if (auth) {
            connection.setRequestProperty("Authorization",
                    "Bearer " + getAccessToken(operatorendpoint.getOperator(), messageContext));

            // Add JWT token header
            org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext)
                    .getAxis2MessageContext();
            Object headers = axis2MessageContext
                    .getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);

            if (headers != null && headers instanceof Map) {
                Map headersMap = (Map) headers;
                String jwtparam = (String) headersMap.get("x-jwt-assertion");
                if (jwtparam != null) {
                    connection.setRequestProperty("x-jwt-assertion", jwtparam);
                }
            }
        }

        if (inclueHeaders) {
            org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext)
                    .getAxis2MessageContext();
            Object headers = axis2MessageContext
                    .getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
            if (headers != null && headers instanceof Map) {
                Map headersMap = (Map) headers;
                Iterator it = headersMap.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry entry = (Map.Entry) it.next();
                    connection.setRequestProperty((String) entry.getKey(), (String) entry.getValue()); // avoids a
                    // ConcurrentModificationException
                }
            }
        }

        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        log.info("Southbound Request URL: " + connection.getRequestMethod() + " " + connection.getURL()
                + " Request ID: " + UID.getRequestID(messageContext));
        if (log.isDebugEnabled()) {
            log.debug("Southbound Request Headers: " + connection.getRequestProperties());
        }
        log.info("Southbound Request Body: " + requestStr + " Request ID: " + UID.getRequestID(messageContext));

        //========================UNICODE PATCH=========================================
        BufferedOutputStream wr = new BufferedOutputStream(connection.getOutputStream());
        wr.write(requestStr.getBytes("UTF-8"));

        wr.flush();
        wr.close();
        //========================UNICODE PATCH=========================================

        /*DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
          wr.writeBytes(requestStr);
         wr.flush();
         wr.close();*/
        statusCode = connection.getResponseCode();
        if ((statusCode != 200) && (statusCode != 201) && (statusCode != 400) && (statusCode != 401)) {
            throw new RuntimeException("Failed : HTTP error code : " + statusCode);
        }

        InputStream is = null;
        if ((statusCode == 200) || (statusCode == 201)) {
            is = connection.getInputStream();
        } else {
            is = connection.getErrorStream();
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String output;
        while ((output = br.readLine()) != null) {
            retStr += output;
        }
        br.close();

        log.info("Southbound Response Status: " + statusCode + " " + connection.getResponseMessage()
                + " Request ID: " + UID.getRequestID(messageContext));
        if (log.isDebugEnabled()) {
            log.debug("Southbound Response Headers: " + connection.getHeaderFields());
        }
        log.info("Southbound Response Body: " + retStr + " Request ID: " + UID.getRequestID(messageContext));

    } catch (Exception e) {
        log.error("[WSRequestService ], makerequest, " + e.getMessage(), e);
        return null;
    } finally {
        if (connection != null) {
            connection.disconnect();
        }

        log.debug(
                "Mo OR DN CallBack : " + isMoCallBack + " requestStr : " + requestStr + " retStr : " + retStr);

        messageContext.setProperty(DataPublisherConstants.RESPONSE_CODE, Integer.toString(statusCode));
        messageContext.setProperty(DataPublisherConstants.MSISDN,
                messageContext.getProperty(MSISDNConstants.USER_MSISDN));
        /*   TODO:This need to consider when publishing request data
             if (isMoCallBack) {
         publishResponseData(statusCode, requestStr, messageContext);
             }else {
                publishResponseData(statusCode, retStr, messageContext);
             }*/
    }
    return retStr;
}

From source file:com.sckftr.android.utils.net.Network.java

/**
 * Call the webservice using the given parameters to construct the request and return the
 * result./*  ww  w  .  j av  a 2  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 handler
 *@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.
 */
static <Out> Out execute(Context context, String urlValue, Method method, Executor<BufferedReader, Out> handler,
        ArrayList<BasicNameValuePair> parameterList, HashMap<String, String> headerMap, boolean isGzipEnabled,
        String userAgent, String postText, UsernamePasswordCredentials credentials,
        boolean isSslValidationEnabled) throws NetworkConnectionException {
    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("&");
            }
        }

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

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

            //Log.d(TAG, "Parameters String: \"" + paramBuilder.toString() + "\"");
        }

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

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

        // 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 = (HttpURLConnection) url.openConnection();
            break;
        case PUT:
        case POST:
            url = new URL(urlValue);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);

            if (paramBuilder.length() > 0) {
                outputText = paramBuilder.toString();
                headerMap.put(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
                headerMap.put(HTTP.CONTENT_LEN, String.valueOf(outputText.getBytes().length));
            } else if (postText != null) {
                outputText = 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) && outputText != null) {
            OutputStream output = null;
            try {
                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.
                    }
                }
            }
        }

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

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

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

        InputStream errorStream = connection.getErrorStream();
        if (errorStream != null) {
            String err = evaluateStream(errorStream, new StringReaderHandler(), isGzip);
            throw new NetworkConnectionException(err, responseCode);
        }

        return evaluateStream(connection.getInputStream(), handler, isGzip);

    } catch (IOException e) {
        Log.e(TAG, "IOException", e);
        throw new NetworkConnectionException(e);
    } catch (KeyManagementException e) {
        Log.e(TAG, "KeyManagementException", e);
        throw new NetworkConnectionException(e);
    } catch (NoSuchAlgorithmException e) {
        Log.e(TAG, "NoSuchAlgorithmException", e);
        throw new NetworkConnectionException(e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:com.phicomm.account.network.NetworkConnectionImpl.java

/**
 * Call the webservice using the given parameters to construct the request and return the
 * result.//from w  ww . jav a2 s .c o  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) throws ConnectionException {
    Thread.dumpStack();
    Log.i("ss", "NetworkConnectionImpl_____________________________________execute__urlValue:" + urlValue);
    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("&");
            }
        }

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

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

                Log.d(TAG, "Parameters String: \"" + paramBuilder.toString() + "\"");
            }

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

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

        // 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) {
                outputText = paramBuilder.toString();
                headerMap.put(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
                headerMap.put(HTTP.CONTENT_LEN, String.valueOf(outputText.getBytes().length));
            } else if (postText != null) {
                outputText = 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) && outputText != null) {
            OutputStream output = null;
            try {
                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.
                    }
                }
            }
        }

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

        int responseCode = connection.getResponseCode();
        boolean isGzip = contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip");
        Log.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);
            throw new ConnectionException(error, responseCode);
        }

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

        if (true) {
            Log.v(TAG, "Response body: ");

            int pos = 0;
            int bodyLength = body.length();
            while (pos < bodyLength) {
                Log.v(TAG, body.substring(pos, Math.min(bodyLength - 1, pos + 200)));
                pos = pos + 200;
            }
        }

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

From source file:com.foxykeep.datadroid.internal.network.NetworkConnectionImpl.java

/**
 * Call the webservice using the given parameters to construct the request and return the
 * result./*from w w w  .  j ava 2 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) 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("&");
            }
        }

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

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

                DataDroidLog.d(TAG, "Parameters String: \"" + paramBuilder.toString() + "\"");
            }

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

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

        // 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) {
                outputText = paramBuilder.toString();
                headerMap.put(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
                headerMap.put(HTTP.CONTENT_LEN, String.valueOf(outputText.getBytes().length));
            } else if (postText != null) {
                outputText = 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) && outputText != null) {
            OutputStream output = null;
            try {
                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.
                    }
                }
            }
        }

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

        int responseCode = connection.getResponseCode();
        boolean isGzip = contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip");
        DataDroidLog.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);
            throw new ConnectionException(error, responseCode);
        }

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

        if (DataDroidLog.canLog(Log.VERBOSE)) {
            DataDroidLog.v(TAG, "Response body: ");

            int pos = 0;
            int bodyLength = body.length();
            while (pos < bodyLength) {
                DataDroidLog.v(TAG, body.substring(pos, Math.min(bodyLength - 1, pos + 200)));
                pos = pos + 200;
            }
        }

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

From source file:com.foxykeep.datadroid.internal.network.NetworkConnectionImplF.java

/**
 * Call the webservice using the given parameters to construct the request and return the
 * result./*from w w  w .  j  a va 2 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, File file) 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("&");
            }
        }

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

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

                DataDroidLog.d(TAG, "Parameters String: \"" + paramBuilder.toString() + "\"");
            }

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

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

        // 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 = (HttpURLConnection) url.openConnection();
            break;
        case PUT:
        case POST:
            url = new URL(urlValue);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);

            if (paramBuilder.length() > 0) {
                outputText = paramBuilder.toString();
                headerMap.put(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
                headerMap.put(HTTP.CONTENT_LEN, String.valueOf(outputText.getBytes().length));
            } else if (postText != null) {
                outputText = 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(READ_OPERATION_TIMEOUT);

        // Set the outputStream content for POST and PUT requests
        if ((method == Method.POST || method == Method.PUT) && outputText != null) {
            OutputStream output = null;
            try {
                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.
                    }
                }
            }
        }

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

        int responseCode = connection.getResponseCode();
        boolean isGzip = contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip");
        DataDroidLog.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) {
            throw new ConnectionException("error", responseCode);
        }

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

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