Example usage for javax.net.ssl HttpsURLConnection setHostnameVerifier

List of usage examples for javax.net.ssl HttpsURLConnection setHostnameVerifier

Introduction

In this page you can find the example usage for javax.net.ssl HttpsURLConnection setHostnameVerifier.

Prototype

public void setHostnameVerifier(HostnameVerifier v) 

Source Link

Document

Sets the HostnameVerifier for this instance.

Usage

From source file:com.camel.trainreserve.JDKHttpsClient.java

public static String doPost(String url, String cookieStr, String ctype, byte[] content, int connectTimeout,
        int readTimeout) throws Exception {
    HttpsURLConnection conn = null;
    OutputStream out = null;/*from  w  w  w .  j  a va 2  s.c om*/
    String rsp = null;
    try {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(null, new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
            //SSLContext.setDefault(ctx);
            conn = getConnection(new URL(url), METHOD_POST, ctype);
            conn.setSSLSocketFactory(ctx.getSocketFactory());

            conn.setRequestProperty("Cookie", cookieStr);
            conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
            conn.setConnectTimeout(connectTimeout);
            conn.setReadTimeout(readTimeout);
        } catch (Exception e) {
            log.error("GET_CONNECTOIN_ERROR, URL = " + url, e);
            throw e;
        }
        try {
            out = conn.getOutputStream();
            out.write(content);
            rsp = getResponseAsString(conn);
        } catch (IOException e) {
            log.error("REQUEST_RESPONSE_ERROR, URL = " + url, e);
            throw e;
        }

    } finally {
        if (out != null) {
            out.close();
        }
        if (conn != null) {
            conn.disconnect();
        }
    }

    return rsp;
}

From source file:com.jms.notify.utils.httpclient.SimpleHttpUtils.java

/**
 *
 * @param urlConn//w ww .  j a v  a  2s .c o  m
 * @param sslVerify
 * @param hostnameVerify
 * @param trustCertFactory
 * @param clientKeyFactory
 */
private static void setSSLSocketFactory(HttpURLConnection urlConn, boolean sslVerify, boolean hostnameVerify,
        TrustKeyStore trustCertFactory, ClientKeyStore clientKeyFactory) {
    try {
        SSLSocketFactory socketFactory = null;
        if (trustCertFactory != null || clientKeyFactory != null || !sslVerify) {
            SSLContext sc = SSLContext.getInstance("SSL");
            TrustManager[] trustManagers = null;
            KeyManager[] keyManagers = null;
            if (trustCertFactory != null) {
                trustManagers = trustCertFactory.getTrustManagerFactory().getTrustManagers();
            }
            if (clientKeyFactory != null) {
                keyManagers = clientKeyFactory.getKeyManagerFactory().getKeyManagers();
            }
            if (!sslVerify) {
                trustManagers = trustAnyManagers;
                hostnameVerify = false;
            }
            sc.init(keyManagers, trustManagers, new java.security.SecureRandom());
            socketFactory = sc.getSocketFactory();
        }

        if (urlConn instanceof HttpsURLConnection) {
            HttpsURLConnection httpsUrlCon = (HttpsURLConnection) urlConn;
            if (socketFactory != null) {
                httpsUrlCon.setSSLSocketFactory(socketFactory);
            }
            //??hostname
            if (!hostnameVerify) {
                httpsUrlCon.setHostnameVerifier(new TrustAnyHostnameVerifier());
            }
        }
        if (urlConn instanceof com.sun.net.ssl.HttpsURLConnection) {
            com.sun.net.ssl.HttpsURLConnection httpsUrlCon = (com.sun.net.ssl.HttpsURLConnection) urlConn;
            if (socketFactory != null) {
                httpsUrlCon.setSSLSocketFactory(socketFactory);
            }
            //??hostname
            if (!hostnameVerify) {
                httpsUrlCon.setHostnameVerifier(new TrustAnyHostnameVerifierOld());
            }
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
}

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

/**
 * Call the webservice using the given parameters to construct the request
 * and return the result./* w  w w  .  j  a va 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, String contentType, List<byte[]> fileByteDates,
        List<String> fileMimeTypes, int httpErrorResCodeFilte, boolean isMulFiles) throws ConnectionException {
    HttpURLConnection connection = null;
    try {
        // Prepare the request information
        if (userAgent == null) {
            userAgent = UserAgentUtils.get(context);
        }
        if (headerMap == null) {
            headerMap = new HashMap<String, String>();
        }
        headerMap.put(HTTP.USER_AGENT, userAgent);
        if (isGzipEnabled) {
            headerMap.put(ACCEPT_ENCODING_HEADER, "gzip");
        }
        headerMap.put(ACCEPT_CHARSET_HEADER, UTF8_CHARSET);
        if (credentials != null) {
            headerMap.put(AUTHORIZATION_HEADER, createAuthenticationHeader(credentials));
        }

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

        // ?
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        logResBodyAndHeader(connection, body);

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

From source file:org.rhq.plugins.www.util.WWWUtils.java

private static void disableCertificateVerification(HttpsURLConnection connection) {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[] {};
        }/*from   w  w w. j  av  a2  s. c  o m*/

        public void checkClientTrusted(X509Certificate[] certs, String authType) {
            return;
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
            return;
        }
    } };
    try {
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        connection.setSSLSocketFactory(sslContext.getSocketFactory());
        connection.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession sslSession) {
                return true;
            }
        });
    } catch (Exception e) {
        Log log = LogFactory.getLog(WWWUtils.class);
        log.warn("Failed to disable certificate validation.", e);
    }
}

From source file:learn.encryption.ssl.SSLContext_Https.java

/**
 * Post??web??,?utf-8//from  w  ww  . j a  v a2s .  c o m
 * 
 * ?UTF8
 * 
 * @param actionUrl
 * @param params
 * @param timeout   
 * @return
 * @throws InvalidParameterException
 * @throws NetWorkException
 * @throws IOException
 * @throws IllegalAccessException 
 * @throws IllegalArgumentException 
 * @throws Exception
 */
public static String post(String url, Map<String, String> params, int timeout)
        throws IOException, IllegalArgumentException, IllegalAccessException {
    if (url == null || url.equals(""))
        throw new IllegalArgumentException("url ");
    if (params == null)
        throw new IllegalArgumentException("params ?");
    if (url.indexOf('?') > 0) {
        url = url
                + "&token=A04BCQULBDgEFB1BQk5cU1NRU19cQU1WWkBPCg0FAwIkCVpZWl1UVExTXFRDSFZSSVlPSkADGhw7HAoQEQMDRFhAWUJYV0hBVE4JAxQLCQlPQ1oiNig/KSsmSEBPGBsAFxkDEkBYSF1eTk1USVldU1FQSEBPFh0OMQhPXEBQSBE=";
    } else {
        url = url
                + "?token=A04BCQULBDgEFB1BQk5cU1NRU19cQU1WWkBPCg0FAwIkCVpZWl1UVExTXFRDSFZSSVlPSkADGhw7HAoQEQMDRFhAWUJYV0hBVE4JAxQLCQlPQ1oiNig/KSsmSEBPGBsAFxkDEkBYSF1eTk1USVldU1FQSEBPFh0OMQhPXEBQSBE=";
    }

    String sb2 = "";
    String BOUNDARY = java.util.UUID.randomUUID().toString();
    String PREFIX = "--", LINEND = "\r\n";
    String MULTIPART_FROM_DATA = "multipart/form-data";
    String CHARSET = "UTF-8";
    // try {
    URL uri = new URL(url);
    HttpsURLConnection conn = (HttpsURLConnection) uri.openConnection();
    // 
    conn.setConnectTimeout(timeout);
    conn.setReadTimeout(timeout);
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("connection", "keep-alive");
    conn.setRequestProperty("Charsert", "UTF-8");
    conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);
    SSLSocketFactory ssf = sslContext.getSocketFactory();
    conn.setSSLSocketFactory(ssf);
    conn.setHostnameVerifier(HOSTNAME_VERIFIER);

    StringBuilder sb = new StringBuilder();
    for (Map.Entry<String, String> entry : params.entrySet()) {
        sb.append(PREFIX);
        sb.append(BOUNDARY);
        sb.append(LINEND);
        sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);
        sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
        sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
        sb.append(LINEND);
        sb.append(entry.getValue());
        sb.append(LINEND);
    }

    DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
    outStream.write(sb.toString().getBytes("UTF-8"));
    InputStream in = null;

    byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
    outStream.write(end_data);
    outStream.flush();

    int res = conn.getResponseCode();
    if (res == 200) {
        in = conn.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
        String line = "";
        for (line = br.readLine(); line != null; line = br.readLine()) {
            sb2 = sb2 + line;
        }
    }
    outStream.close();
    conn.disconnect();
    return sb2;
}

From source file:com.orange.oidc.secproxy_service.HttpOpenidConnect.java

static public HttpURLConnection getHUC(String address) {
    HttpURLConnection http = null;

    Log.d(TAG, "getHUC for " + address);

    try {//from   w  ww . j  a v a  2 s  . c  om
        URL url = new URL(address);

        if (url.getProtocol().equalsIgnoreCase("https")) {

            Log.d(TAG, "getHUC https");

            // only use trustAllHosts and DO_NOT_VERIFY in development process
            trustAllHosts();
            HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
            https.setHostnameVerifier(DO_NOT_VERIFY);
            http = https;
        } else {
            Log.d(TAG, "getHUC http");
            http = (HttpURLConnection) url.openConnection();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    Log.d(TAG, "getHUC return connection");

    return http;
}

From source file:org.wso2.carbon.automation.test.utils.http.client.HttpsURLConnectionClient.java

public static HttpsResponse deleteWithBasicAuth(String uri, String contentType, String userName,
        String password) throws IOException {
    if (uri.startsWith("https://")) {
        URL url = new URL(uri);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("DELETE");
        String encode = new String(
                new org.apache.commons.codec.binary.Base64().encode((userName + ":" + password).getBytes()))
                        .replaceAll("\n", "");
        ;/*from   ww w  .  ja  v a 2s  .  c  om*/
        conn.setRequestProperty("Authorization", "Basic " + encode);
        if (contentType != null) {
            conn.setRequestProperty("Content-Type", contentType);
        }
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);
        conn.setHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        conn.connect();
        StringBuilder sb = new StringBuilder();
        BufferedReader rd = null;
        try {
            rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), Charset.defaultCharset()));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
        } catch (FileNotFoundException ignored) {
        } finally {
            if (rd != null) {
                rd.close();
            }
            conn.disconnect();
        }
        return new HttpsResponse(sb.toString(), conn.getResponseCode());
    }
    return null;
}

From source file:org.wso2.carbon.automation.test.utils.http.client.HttpsURLConnectionClient.java

public static HttpsResponse postWithBasicAuth(String uri, String requestQuery, String contentType,
        String userName, String password) throws IOException {
    if (uri.startsWith("https://")) {
        URL url = new URL(uri);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        String encode = new String(
                new org.apache.commons.codec.binary.Base64().encode((userName + ":" + password).getBytes()))
                        .replaceAll("\n", "");
        conn.setRequestProperty("Authorization", "Basic " + encode);
        conn.setDoOutput(true); // Triggers POST.
        conn.setRequestProperty("Content-Type", contentType);
        conn.setRequestProperty("charset", "utf-8");
        conn.setRequestProperty("Content-Length", "" + Integer.toString(requestQuery.getBytes().length));
        conn.setUseCaches(false);/*www  . j  a  va2s. com*/
        conn.setHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(requestQuery);
        conn.setReadTimeout(10000);
        conn.connect();
        System.out.println(conn.getRequestMethod());
        // Get the response
        StringBuilder sb = new StringBuilder();
        BufferedReader rd = null;
        try {
            rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), Charset.defaultCharset()));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
        } catch (FileNotFoundException ignored) {
        } finally {
            if (rd != null) {
                rd.close();
            }
            wr.flush();
            wr.close();
            conn.disconnect();
        }
        return new HttpsResponse(sb.toString(), conn.getResponseCode());
    }
    return null;
}

From source file:org.wso2.carbon.automation.test.utils.http.client.HttpsURLConnectionClient.java

public static HttpsResponse putWithBasicAuth(String uri, String requestQuery, String contentType,
        String userName, String password) throws IOException {
    if (uri.startsWith("https://")) {
        URL url = new URL(uri);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        String encode = new String(
                new org.apache.commons.codec.binary.Base64().encode((userName + ":" + password).getBytes()))
                        .replaceAll("\n", "");
        ;//w ww . j  av a 2s .  com
        conn.setRequestProperty("Authorization", "Basic " + encode);
        conn.setDoOutput(true); // Triggers POST.
        conn.setRequestProperty("Content-Type", contentType);
        conn.setRequestProperty("charset", "utf-8");
        conn.setRequestProperty("Content-Length", "" + Integer.toString(requestQuery.getBytes().length));
        conn.setUseCaches(false);
        conn.setHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(requestQuery);
        conn.setReadTimeout(10000);
        conn.connect();
        // Get the response
        StringBuilder sb = new StringBuilder();
        BufferedReader rd = null;
        try {
            rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), Charset.defaultCharset()));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
        } catch (FileNotFoundException ignored) {
        } finally {
            if (rd != null) {
                rd.close();
            }
            wr.flush();
            wr.close();
            conn.disconnect();
        }
        return new HttpsResponse(sb.toString(), conn.getResponseCode());
    }
    return null;
}

From source file:org.wso2.carbon.automation.test.utils.http.client.HttpsURLConnectionClient.java

public static HttpsResponse postWithBasicAuth(String uri, String requestQuery, String userName, String password)
        throws IOException {
    if (uri.startsWith("https://")) {
        URL url = new URL(uri);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        String encode = new String(
                new org.apache.commons.codec.binary.Base64().encode((userName + ":" + password).getBytes()))
                        .replaceAll("\n", "");
        ;//  w  w  w  .  j  a v a 2 s.c om
        conn.setRequestProperty("Authorization", "Basic " + encode);
        conn.setDoOutput(true); // Triggers POST.
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("charset", "utf-8");
        conn.setRequestProperty("Content-Length", "" + Integer.toString(requestQuery.getBytes().length));
        conn.setUseCaches(false);
        conn.setHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(requestQuery);
        conn.setReadTimeout(10000);
        conn.connect();
        System.out.println(conn.getRequestMethod());
        // Get the response
        StringBuilder sb = new StringBuilder();
        BufferedReader rd = null;
        try {
            rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), Charset.defaultCharset()));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
            return new HttpsResponse(sb.toString(), conn.getResponseCode());
        } catch (FileNotFoundException ignored) {
        } finally {
            if (rd != null) {
                rd.close();
            }
            wr.flush();
            wr.close();
            conn.disconnect();
        }
    }
    return null;
}