Example usage for java.net HttpURLConnection getHeaderFields

List of usage examples for java.net HttpURLConnection getHeaderFields

Introduction

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

Prototype

public Map<String, List<String>> getHeaderFields() 

Source Link

Document

Returns an unmodifiable Map of the header fields.

Usage

From source file:com.acc.android.network.operator.base.BaseHttpOperator.java

private String openRequest(String url, RequestMethod requestMethod, Object paramObject) {
    if (!this.checkNetWork()) {
        // return this.notNetError;
    }//from w  w w. j  a  v  a  2 s .  c o m
    HttpURLConnection conn = null;
    InputStream inputStream = null;
    String response = null;
    PrintWriter out = null;
    try {
        // if (AppLibConstant.isUseLog()) {
        LogUtil.info(this, "Begin a request--->>>>>>>>>>");
        // }
        // try {
        // url = URLEncoder.encode(url, HttpConstant.ENCODE);
        // } catch (UnsupportedEncodingException e) {
        // // TODO Auto-generated catch block
        // e.printStackTrace();
        // }
        if (requestMethod == requestMethod.GET && paramObject != null) {
            // try {
            url = url + "?" + this.encodeUrlParam(paramObject);
            // } catch (UnsupportedEncodingException e) {
            // // TODO Auto-generated catch block
            // e.printStackTrace();
            // }
            // http://192.168.15.204:82/agcom/rest/roadRest/getBestRoad?id=2&xy=56536.156809,13853.484204
            // 56364.173164,12955.347386
        }
        // if (AppLibConstant.isUseLog()) {
        LogUtil.info(this, "url:", url);
        LogUtil.info(this, "requestMethod:", requestMethod);
        LogUtil.info(this, "paramObject:", paramObject);
        // }
        // url = url.replace(" ", "%20");
        conn = (HttpURLConnection) new URL(url).openConnection();
        // System.out
        // .println("this.sessionStr == null" + this.sessionStr == null);
        // System.out.println(this.sessionStr == null);
        if (this.sessionStr != null) {
            conn.setRequestProperty("cookie", sessionStr);
        }
        conn.setConnectTimeout(5 * 1000);
        if (requestMethod == RequestMethod.GET) {
            // conn.setRequestMethod(method);
            // if (isMultipart) {
            // conn.setRequestProperty("Content-Type",
            // "multipart/form-data;");
            // } else {
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencode");
            // }
            conn.connect();
        } else {
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            // http: //
            // 192.168.16.16:8089/agcom/rest/system/locateDiscode/231/10//
            // Content-Type
            // if (isMultipart) {
            // conn.setRequestProperty("Content-Type",
            // "multipart/form-data;");
            // } else {
            // conn.setRequestProperty("Content-Type",
            // "application/x-www-form-urlencode");

            // }
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencode");
            // conn.connect();
            if (paramObject != null) {
                conn.getOutputStream().write(this.encodeUrlParam(paramObject).getBytes(HttpConstant.ENCODE));
                // out = new PrintWriter(conn.getOutputStream());
                // out.print(paramObject);
                // out.flush();
            }
        }
        inputStream = conn.getInputStream();
        response = read(inputStream);
        // if (AppLibConstant.isUseLog()) {
        LogUtil.info(this, "response:", response);
        // }
        if (this.sessionStr == null) {
            Map<String, List<String>> cookies = conn.getHeaderFields();
            // this.cookieHeader = conn.getg
            for (String key : cookies.keySet()) {
                // System.out.println("sdfdsfd:" + key);
                if (key == null) {
                    continue;
                }
                if ("set-cookie".equals(key.toLowerCase())) {
                    List<String> values = cookies.get(key);
                    String sessionStrTemp = "";
                    for (String value : values) {
                        sessionStrTemp += value;
                        sessionStrTemp += ";";
                        // conn.addRequestProperty("set-cookie", string);
                    }
                    // loginSessionStrTemp =
                    // loginSessionStrTemp.substring(0,
                    // loginSessionStrTemp.length() - 1);
                    // System.out.println("loginSessionStrTemp:"
                    // + loginSessionStrTemp);
                    this.sessionStr = sessionStrTemp;
                    this.sessionKey = key;
                    // OldHttpUtil.LOGINSESSIONSTR = sessionStrTemp;
                    // BaseHttpManager.sessionStr = loginSessionStrTemp;
                    break;
                }
            }
            // System.out.println("sessionStr:" + sessionStr);
        }
        // System.out.println("openUrl:response:" + response);
    } catch (Exception e) {
        // if (AppLibConstant.isUseLog()) {
        LogUtil.info(this, "End a request with exception below---XXXXXXXXXX");
        // }
        e.printStackTrace();
        return response;
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (out != null) {
            try {
                out.close();
            } catch (Exception exception) {
                exception.printStackTrace();
            }
        }
    }
    // if (AppLibConstant.isUseLog()) {
    LogUtil.info(this, "End a request successfully---VVVVVVVVVV");
    // }
    return response;
}

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

/**
 *
 * @param url//from   ww  w  . j a v  a2  s  . c o m
 * @param requestStr
 * @param messageContext
 * @return
 */
public String makeWalletRequest(OperatorEndpoint operatorendpoint, String url, String requestStr, boolean auth,
        MessageContext messageContext, boolean inclueHeaders) {

    String retStr = "";
    int statusCode = 0;

    URL neturl;
    HttpURLConnection connection = null;

    try {

        neturl = new URL(url);
        connection = (HttpURLConnection) neturl.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Accept-Charset", "UTF-8");//ADDED
        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=========================================

        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();
        }
        messageContext.setProperty(DataPublisherConstants.RESPONSE_CODE, Integer.toString(statusCode));
        messageContext.setProperty(DataPublisherConstants.MSISDN,
                messageContext.getProperty(MSISDNConstants.USER_MSISDN));
        publishWalletPaymentData(statusCode, retStr, messageContext);
    }

    return retStr;
}

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

/**
 * Make delete request./*  ww  w .  ja va 2  s . c  o m*/
 *
 * @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 makeDeleteRequest(OperatorEndpoint operatorendpoint, String url, String requestStr, boolean auth,
        MessageContext messageContext, boolean inclueHeaders) {

    int statusCode = 0;
    String retStr = "";
    URL neturl;
    HttpURLConnection connection = null;

    try {

        // String Authtoken = AccessToken;
        // //FileUtil.getApplicationProperty("wow.api.bearer.token");
        // DefaultHttpClient httpClient = new DefaultHttpClient();

        String encurl = (requestStr != null) ? url + requestStr : url;
        neturl = new URL(encurl);
        connection = (HttpURLConnection) neturl.openConnection();
        connection.setRequestMethod("DELETE");
        connection.setRequestProperty("Content-Type", "application/json");

        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);

        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));

        if (requestStr != null) {
            connection.setDoOutput(true);
            DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
            wr.writeBytes(requestStr);
            wr.flush();
            wr.close();
        }

        statusCode = connection.getResponseCode();
        log.info("response code: " + statusCode);

        if ((statusCode != 200) && (statusCode != 201) && (statusCode != 400) && (statusCode != 401)
                && (statusCode != 204)) {
            throw new RuntimeException("Failed : HTTP error code : " + statusCode);
        }

        InputStream is = null;
        if ((statusCode == 200) || (statusCode == 201) || (statusCode == 204)) {
            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();
        }
    }
    return retStr;
}

From source file:org.pixmob.httpclient.HttpRequestBuilder.java

public HttpResponse execute() throws HttpClientException {
    HttpURLConnection conn = null;
    UncloseableInputStream payloadStream = null;
    try {/*  w  w w  .j  av  a2  s. c o m*/
        if (parameters != null && !parameters.isEmpty()) {
            final StringBuilder buf = new StringBuilder(256);
            if (HTTP_GET.equals(method) || HTTP_HEAD.equals(method)) {
                buf.append('?');
            }

            int paramIdx = 0;
            for (final Map.Entry<String, String> e : parameters.entrySet()) {
                if (paramIdx != 0) {
                    buf.append("&");
                }
                final String name = e.getKey();
                final String value = e.getValue();
                buf.append(URLEncoder.encode(name, CONTENT_CHARSET)).append("=")
                        .append(URLEncoder.encode(value, CONTENT_CHARSET));
                ++paramIdx;
            }

            if (!contentSet
                    && (HTTP_POST.equals(method) || HTTP_DELETE.equals(method) || HTTP_PUT.equals(method))) {
                try {
                    content = buf.toString().getBytes(CONTENT_CHARSET);
                } catch (UnsupportedEncodingException e) {
                    // Unlikely to happen.
                    throw new HttpClientException("Encoding error", e);
                }
            } else {
                uri += buf;
            }
        }

        conn = (HttpURLConnection) new URL(uri).openConnection();
        conn.setConnectTimeout(hc.getConnectTimeout());
        conn.setReadTimeout(hc.getReadTimeout());
        conn.setAllowUserInteraction(false);
        conn.setInstanceFollowRedirects(false);
        conn.setRequestMethod(method);
        conn.setUseCaches(false);
        conn.setDoInput(true);

        if (headers != null && !headers.isEmpty()) {
            for (final Map.Entry<String, List<String>> e : headers.entrySet()) {
                final List<String> values = e.getValue();
                if (values != null) {
                    final String name = e.getKey();
                    for (final String value : values) {
                        conn.addRequestProperty(name, value);
                    }
                }
            }
        }

        if (cookies != null && !cookies.isEmpty()
                || hc.getInMemoryCookies() != null && !hc.getInMemoryCookies().isEmpty()) {
            final StringBuilder cookieHeaderValue = new StringBuilder(256);
            prepareCookieHeader(cookies, cookieHeaderValue);
            prepareCookieHeader(hc.getInMemoryCookies(), cookieHeaderValue);
            conn.setRequestProperty("Cookie", cookieHeaderValue.toString());
        }

        final String userAgent = hc.getUserAgent();
        if (userAgent != null) {
            conn.setRequestProperty("User-Agent", userAgent);
        }

        conn.setRequestProperty("Connection", "close");
        conn.setRequestProperty("Location", uri);
        conn.setRequestProperty("Referrer", uri);
        conn.setRequestProperty("Accept-Encoding", "gzip,deflate");
        conn.setRequestProperty("Accept-Charset", CONTENT_CHARSET);

        if (conn instanceof HttpsURLConnection) {
            setupSecureConnection(hc.getContext(), (HttpsURLConnection) conn);
        }

        for (final HttpRequestHandler connHandler : reqHandlers) {
            try {
                connHandler.onRequest(conn);
            } catch (HttpClientException e) {
                throw e;
            } catch (Exception e) {
                throw new HttpClientException("Failed to prepare request to " + uri, e);
            }
        }

        // It seems that when writing content starts the connection
        if (HTTP_POST.equals(method) || HTTP_DELETE.equals(method) || HTTP_PUT.equals(method)) {

            if (content == null) {
                noContent();
            }

            conn.setDoOutput(true);
            if (!contentSet) {
                conn.setRequestProperty("Content-Type",
                        "application/x-www-form-urlencoded; charset=" + CONTENT_CHARSET);
            } else if (contentType != null) {
                conn.setRequestProperty("Content-Type", contentType);
            }
            conn.setFixedLengthStreamingMode(content.length);

            final OutputStream out = conn.getOutputStream();
            out.write(content);
            out.flush();
        }

        conn.connect();

        final int statusCode = conn.getResponseCode();
        if (statusCode == -1) {
            throw new HttpClientException("Invalid response from " + uri);
        }
        if (!expectedStatusCodes.isEmpty() && !expectedStatusCodes.contains(statusCode)) {
            throw new HttpClientException(
                    "Expected status code " + expectedStatusCodes + ", got " + statusCode);
        } else if (expectedStatusCodes.isEmpty() && statusCode / 100 != 2) {
            throw new HttpClientException("Expected status code 2xx, got " + statusCode);
        }

        final Map<String, List<String>> headerFields = conn.getHeaderFields();
        final Map<String, String> inMemoryCookies = hc.getInMemoryCookies();
        if (headerFields != null) {
            final List<String> newCookies = headerFields.get("Set-Cookie");
            if (newCookies != null) {
                for (final String newCookie : newCookies) {
                    final String rawCookie = newCookie.split(";", 2)[0];
                    final int i = rawCookie.indexOf('=');
                    final String name = rawCookie.substring(0, i);
                    final String value = rawCookie.substring(i + 1);
                    inMemoryCookies.put(name, value);
                }
            }
        }

        if (isStatusCodeError(statusCode)) {
            // Got an error: cannot read input.
            payloadStream = new UncloseableInputStream(getErrorStream(conn));
        } else {
            payloadStream = new UncloseableInputStream(getInputStream(conn));
        }
        final HttpResponse resp = new HttpResponse(statusCode, payloadStream,
                headerFields == null ? NO_HEADERS : headerFields, inMemoryCookies);
        if (handler != null) {
            try {
                handler.onResponse(resp);
            } catch (HttpClientException e) {
                throw e;
            } catch (Exception e) {
                throw new HttpClientException("Error in response handler", e);
            }
        } else {
            final File temp = File.createTempFile("httpclient-req-", ".cache", hc.getContext().getCacheDir());
            resp.preload(temp);
            temp.delete();
        }
        return resp;
    } catch (SocketTimeoutException e) {
        if (handler != null) {
            try {
                handler.onTimeout();
                return null;
            } catch (HttpClientException e2) {
                throw e2;
            } catch (Exception e2) {
                throw new HttpClientException("Error in response handler", e2);
            }
        } else {
            throw new HttpClientException("Response timeout from " + uri, e);
        }
    } catch (IOException e) {
        throw new HttpClientException("Connection failed to " + uri, e);
    } finally {
        if (conn != null) {
            if (payloadStream != null) {
                // Fully read Http response:
                // http://docs.oracle.com/javase/6/docs/technotes/guides/net/http-keepalive.html
                try {
                    while (payloadStream.read(buffer) != -1) {
                        ;
                    }
                } catch (IOException ignore) {
                }
                payloadStream.forceClose();
            }
            conn.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  v  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 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();
        }
    }
}

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

/**
 * Make request./*from  ww  w .  j a v  a2  s .c  o m*/
 *
 * @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:org.kymjs.kjframe.http.httpclient.HttpRequestBuilder.java

public HttpResponse execute() throws HttpClientException {
    HttpURLConnection conn = null;
    UncloseableInputStream payloadStream = null;
    try {//  w  w w  . j  av  a  2s  .c o m
        if (parameters != null && !parameters.isEmpty()) {
            final StringBuilder buf = new StringBuilder(256);
            if (HTTP_GET.equals(method) || HTTP_HEAD.equals(method)) {
                buf.append('?');
            }

            int paramIdx = 0;
            for (final Map.Entry<String, String> e : parameters.entrySet()) {
                if (paramIdx != 0) {
                    buf.append("&");
                }
                final String name = e.getKey();
                final String value = e.getValue();
                buf.append(URLEncoder.encode(name, CONTENT_CHARSET)).append("=")
                        .append(URLEncoder.encode(value, CONTENT_CHARSET));
                ++paramIdx;
            }

            if (!contentSet
                    && (HTTP_POST.equals(method) || HTTP_DELETE.equals(method) || HTTP_PUT.equals(method))) {
                try {
                    content = buf.toString().getBytes(CONTENT_CHARSET);
                } catch (UnsupportedEncodingException e) {
                    // Unlikely to happen.
                    throw new HttpClientException("Encoding error", e);
                }
            } else {
                uri += buf;
            }
        }

        conn = (HttpURLConnection) new URL(uri).openConnection();
        conn.setConnectTimeout(hc.getConnectTimeout());
        conn.setReadTimeout(hc.getReadTimeout());
        conn.setAllowUserInteraction(false);
        conn.setInstanceFollowRedirects(false);
        conn.setRequestMethod(method);
        conn.setUseCaches(false);
        conn.setDoInput(true);

        if (headers != null && !headers.isEmpty()) {
            for (final Map.Entry<String, List<String>> e : headers.entrySet()) {
                final List<String> values = e.getValue();
                if (values != null) {
                    final String name = e.getKey();
                    for (final String value : values) {
                        conn.addRequestProperty(name, value);
                    }
                }
            }
        }

        if (cookies != null && !cookies.isEmpty()
                || hc.getInMemoryCookies() != null && !hc.getInMemoryCookies().isEmpty()) {
            final StringBuilder cookieHeaderValue = new StringBuilder(256);
            prepareCookieHeader(cookies, cookieHeaderValue);
            prepareCookieHeader(hc.getInMemoryCookies(), cookieHeaderValue);
            conn.setRequestProperty("Cookie", cookieHeaderValue.toString());
        }

        final String userAgent = hc.getUserAgent();
        if (userAgent != null) {
            conn.setRequestProperty("User-Agent", userAgent);
        }

        conn.setRequestProperty("Connection", "close");
        conn.setRequestProperty("Location", uri);
        conn.setRequestProperty("Referrer", uri);
        conn.setRequestProperty("Accept-Encoding", "gzip,deflate");
        conn.setRequestProperty("Accept-Charset", CONTENT_CHARSET);

        if (conn instanceof HttpsURLConnection) {
            setupSecureConnection(hc.getContext(), (HttpsURLConnection) conn);
        }

        if (HTTP_POST.equals(method) || HTTP_DELETE.equals(method) || HTTP_PUT.equals(method)) {
            if (content != null) {
                conn.setDoOutput(true);
                if (!contentSet) {
                    conn.setRequestProperty("Content-Type",
                            "application/x-www-form-urlencoded; charset=" + CONTENT_CHARSET);
                } else if (contentType != null) {
                    conn.setRequestProperty("Content-Type", contentType);
                }
                conn.setFixedLengthStreamingMode(content.length);

                final OutputStream out = conn.getOutputStream();
                out.write(content);
                out.flush();
            } else {
                conn.setFixedLengthStreamingMode(0);
            }
        }

        for (final HttpRequestHandler connHandler : reqHandlers) {
            try {
                connHandler.onRequest(conn);
            } catch (HttpClientException e) {
                throw e;
            } catch (Exception e) {
                throw new HttpClientException("Failed to prepare request to " + uri, e);
            }
        }

        conn.connect();

        final int statusCode = conn.getResponseCode();
        if (statusCode == -1) {
            throw new HttpClientException("Invalid response from " + uri);
        }
        if (!expectedStatusCodes.isEmpty() && !expectedStatusCodes.contains(statusCode)) {
            throw new HttpClientException(
                    "Expected status code " + expectedStatusCodes + ", got " + statusCode);
        } else if (expectedStatusCodes.isEmpty() && statusCode / 100 != 2) {
            throw new HttpClientException("Expected status code 2xx, got " + statusCode);
        }

        final Map<String, List<String>> headerFields = conn.getHeaderFields();
        final Map<String, String> inMemoryCookies = hc.getInMemoryCookies();
        if (headerFields != null) {
            final List<String> newCookies = headerFields.get("Set-Cookie");
            if (newCookies != null) {
                for (final String newCookie : newCookies) {
                    final String rawCookie = newCookie.split(";", 2)[0];
                    final int i = rawCookie.indexOf('=');
                    final String name = rawCookie.substring(0, i);
                    final String value = rawCookie.substring(i + 1);
                    inMemoryCookies.put(name, value);
                }
            }
        }

        if (isStatusCodeError(statusCode)) {
            // Got an error: cannot read input.
            payloadStream = new UncloseableInputStream(getErrorStream(conn));
        } else {
            payloadStream = new UncloseableInputStream(getInputStream(conn));
        }
        final HttpResponse resp = new HttpResponse(statusCode, payloadStream,
                headerFields == null ? NO_HEADERS : headerFields, inMemoryCookies);
        if (handler != null) {
            try {
                handler.onResponse(resp);
            } catch (HttpClientException e) {
                e.printStackTrace();
                throw e;
            } catch (Exception e) {
                throw new HttpClientException("Error in response handler", e);
            }
        } else {
            final File temp = File.createTempFile("httpclient-req-", ".cache", hc.getContext().getCacheDir());
            resp.preload(temp);
            temp.delete();
        }
        return resp;
    } catch (SocketTimeoutException e) {
        if (handler != null) {
            try {
                handler.onTimeout();
                return null;
            } catch (HttpClientException e2) {
                throw e2;
            } catch (Exception e2) {
                throw new HttpClientException("Error in response handler", e2);
            }
        } else {
            throw new HttpClientException("Response timeout from " + uri, e);
        }
    } catch (IOException e) {
        throw new HttpClientException("Connection failed to " + uri, e);
    } finally {
        if (conn != null) {
            if (payloadStream != null) {
                // Fully read Http response:
                // http://docs.oracle.com/javase/6/docs/technotes/guides/net/http-keepalive.html
                try {
                    while (payloadStream.read(buffer) != -1) {
                        ;
                    }
                } catch (IOException ignore) {
                }
                payloadStream.forceClose();
            }
            conn.disconnect();
        }
    }
}

From source file:org.alfresco.mobile.android.api.network.NetworkHttpInvoker.java

protected Response invoke(UrlBuilder url, String method, String contentType, Map<String, String> headers,
        Output writer, BindingSession session, BigInteger offset, BigInteger length) {
    try {//w ww .j a  v  a2s  .  c  o  m
        // log before connect
        //Log.d("URL", url.toString());
        if (LOG.isDebugEnabled()) {
            LOG.debug(method + " " + url);
        }

        // connect
        HttpURLConnection conn = getHttpURLConnection(new URL(url.toString()));
        conn.setRequestMethod(method);
        conn.setDoInput(true);
        conn.setDoOutput(writer != null);
        conn.setAllowUserInteraction(false);
        conn.setUseCaches(false);
        conn.setRequestProperty(HTTP.USER_AGENT, ClientVersion.OPENCMIS_CLIENT);

        // timeouts
        int connectTimeout = session.get(SessionParameter.CONNECT_TIMEOUT, -1);
        if (connectTimeout >= 0) {
            conn.setConnectTimeout(connectTimeout);
        }

        int readTimeout = session.get(SessionParameter.READ_TIMEOUT, -1);
        if (readTimeout >= 0) {
            conn.setReadTimeout(readTimeout);
        }

        // set content type
        if (contentType != null) {
            conn.setRequestProperty(HTTP.CONTENT_TYPE, contentType);
        }
        // set other headers
        if (headers != null) {
            for (Map.Entry<String, String> header : headers.entrySet()) {
                conn.addRequestProperty(header.getKey(), header.getValue());
            }
        }

        // authenticate
        AuthenticationProvider authProvider = CmisBindingsHelper.getAuthenticationProvider(session);
        if (authProvider != null) {
            Map<String, List<String>> httpHeaders = authProvider.getHTTPHeaders(url.toString());
            if (httpHeaders != null) {
                for (Map.Entry<String, List<String>> header : httpHeaders.entrySet()) {
                    if (header.getValue() != null) {
                        for (String value : header.getValue()) {
                            conn.addRequestProperty(header.getKey(), value);
                        }
                    }
                }
            }

            if (conn instanceof HttpsURLConnection) {
                SSLSocketFactory sf = authProvider.getSSLSocketFactory();
                if (sf != null) {
                    ((HttpsURLConnection) conn).setSSLSocketFactory(sf);
                }

                HostnameVerifier hv = authProvider.getHostnameVerifier();
                if (hv != null) {
                    ((HttpsURLConnection) conn).setHostnameVerifier(hv);
                }
            }
        }

        // range
        if ((offset != null) || (length != null)) {
            StringBuilder sb = new StringBuilder("bytes=");

            if ((offset == null) || (offset.signum() == -1)) {
                offset = BigInteger.ZERO;
            }

            sb.append(offset.toString());
            sb.append("-");

            if ((length != null) && (length.signum() == 1)) {
                sb.append(offset.add(length.subtract(BigInteger.ONE)).toString());
            }

            conn.setRequestProperty("Range", sb.toString());
        }

        // compression
        Object compression = session.get(AlfrescoSession.HTTP_ACCEPT_ENCODING);
        if (compression == null) {
            conn.setRequestProperty("Accept-Encoding", "");
        } else {
            Boolean compressionValue;
            try {
                compressionValue = Boolean.parseBoolean(compression.toString());
                if (compressionValue) {
                    conn.setRequestProperty("Accept-Encoding", "gzip,deflate");
                } else {
                    conn.setRequestProperty("Accept-Encoding", "");
                }
            } catch (Exception e) {
                conn.setRequestProperty("Accept-Encoding", compression.toString());
            }
        }

        // locale
        if (session.get(AlfrescoSession.HTTP_ACCEPT_LANGUAGE) instanceof String
                && session.get(AlfrescoSession.HTTP_ACCEPT_LANGUAGE) != null) {
            conn.setRequestProperty("Accept-Language",
                    session.get(AlfrescoSession.HTTP_ACCEPT_LANGUAGE).toString());
        }

        // send data
        if (writer != null) {
            Object chunkTransfert = session.get(AlfrescoSession.HTTP_CHUNK_TRANSFERT);
            if (chunkTransfert != null && Boolean.parseBoolean(chunkTransfert.toString())) {
                conn.setRequestProperty(HTTP.TRANSFER_ENCODING, "chunked");
                conn.setChunkedStreamingMode(0);
            }

            conn.setConnectTimeout(900000);

            OutputStream connOut = null;

            Object clientCompression = session.get(SessionParameter.CLIENT_COMPRESSION);
            if ((clientCompression != null) && Boolean.parseBoolean(clientCompression.toString())) {
                conn.setRequestProperty(HTTP.CONTENT_ENCODING, "gzip");
                connOut = new GZIPOutputStream(conn.getOutputStream(), 4096);
            } else {
                connOut = conn.getOutputStream();
            }

            OutputStream out = new BufferedOutputStream(connOut, BUFFER_SIZE);
            writer.write(out);
            out.flush();
        }

        // connect
        conn.connect();

        // get stream, if present
        int respCode = conn.getResponseCode();
        InputStream inputStream = null;
        if ((respCode == HttpStatus.SC_OK) || (respCode == HttpStatus.SC_CREATED)
                || (respCode == HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION)
                || (respCode == HttpStatus.SC_PARTIAL_CONTENT)) {
            inputStream = conn.getInputStream();
        }

        // log after connect
        if (LOG.isTraceEnabled()) {
            LOG.trace(method + " " + url + " > Headers: " + conn.getHeaderFields());
        }

        // forward response HTTP headers
        if (authProvider != null) {
            authProvider.putResponseHeaders(url.toString(), respCode, conn.getHeaderFields());
        }

        // get the response
        return new Response(respCode, conn.getResponseMessage(), conn.getHeaderFields(), inputStream,
                conn.getErrorStream());
    } catch (Exception e) {
        throw new CmisConnectionException("Cannot access " + url + ": " + e.getMessage(), e);
    }
}

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  w  w. j  ava 2 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   ww w.j  av  a  2  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 {
    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();
        }
    }
}