Example usage for javax.net.ssl HttpsURLConnection getInputStream

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

Introduction

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

Prototype

public InputStream getInputStream() throws IOException 

Source Link

Document

Returns an input stream that reads from this open connection.

Usage

From source file:com.adobe.ibm.watson.traits.impl.WatsonServiceClient.java

/**
 * Fetches the IBM Watson Personal Insights report using the user's Twitter Timeline.
 * @param language// ww  w  .j a va  2  s.co m
 * @param tweets
 * @param resource
 * @return
 * @throws Exception
 */
public String getWatsonScore(String language, String tweets, Resource resource) throws Exception {

    HttpsURLConnection connection = null;

    // Check if the username and password have been injected to the service.
    // If not, extract them from the cloud service configuration attached to the page.
    if (this.username == null || this.password == null) {
        getWatsonCloudSettings(resource);
    }

    // Build the request to IBM Watson.
    log.info("The Base Url is: " + this.baseUrl);
    String encodedCreds = getBasicAuthenticationEncoding();
    URL url = new URL(this.baseUrl + "/v2/profile");

    connection = (HttpsURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setRequestProperty("Accept", "application/json");
    connection.setRequestProperty("Content-Language", language);
    connection.setRequestProperty("Accept-Language", "en-us");
    connection.setRequestProperty("Content-Type", ContentType.TEXT_PLAIN.toString());
    connection.setRequestProperty("Authorization", "Basic " + encodedCreds);
    connection.setUseCaches(false);
    connection.getOutputStream().write(tweets.getBytes());
    connection.getOutputStream().flush();
    connection.connect();

    log.info("Parsing response from Watson");
    StringBuilder str = new StringBuilder();

    BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String line = "";
    while ((line = br.readLine()) != null) {
        str.append(line + System.getProperty("line.separator"));
    }

    if (connection.getResponseCode() != 200) {
        // The call failed, throw an exception.
        log.error(connection.getResponseCode() + " : " + connection.getResponseMessage());
        connection.disconnect();
        throw new Exception("IBM Watson Server responded with an error: " + connection.getResponseMessage());
    } else {
        connection.disconnect();
        return str.toString();
    }
}

From source file:com.gloriouseggroll.LastFMAPI.java

@SuppressWarnings({ "null", "SleepWhileInLoop", "UseSpecificCatch" })
private JSONObject GetData(request_type type, String url, String post) {
    Date start = new Date();
    Date preconnect = start;/*from  w  ww.  j ava2 s. c  o  m*/
    Date postconnect = start;
    Date prejson = start;
    Date postjson = start;
    JSONObject j = new JSONObject("{}");
    BufferedInputStream i = null;
    String rawcontent = "";
    int available = 0;
    int responsecode = 0;
    long cl = 0;

    try {

        URL u = new URL(url);
        HttpsURLConnection c = (HttpsURLConnection) u.openConnection();

        c.setRequestMethod(type.name());

        c.setUseCaches(false);
        c.setDefaultUseCaches(false);
        c.setConnectTimeout(5000);
        c.setReadTimeout(5000);
        c.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 QuorraBot/2015");
        c.setRequestProperty("Content-Type", "application/json-rpc");
        c.setRequestProperty("Content-length", "0");

        if (!post.isEmpty()) {
            c.setDoOutput(true);
        }

        preconnect = new Date();
        c.connect();
        postconnect = new Date();

        if (!post.isEmpty()) {
            try (BufferedOutputStream o = new BufferedOutputStream(c.getOutputStream())) {
                IOUtils.write(post, o);
            }
        }

        String content;
        cl = c.getContentLengthLong();
        responsecode = c.getResponseCode();

        if (c.getResponseCode() == 200) {
            i = new BufferedInputStream(c.getInputStream());
        } else {
            i = new BufferedInputStream(c.getErrorStream());
        }

        /*
         * if (i != null) { available = i.available();
         *
         * while (available == 0 && (new Date().getTime() -
         * postconnect.getTime()) < 450) { Thread.sleep(500); available =
         * i.available(); }
         *
         * if (available == 0) { i = new
         * BufferedInputStream(c.getErrorStream());
         *
         * if (i != null) { available = i.available(); } } }
         *
         * if (available == 0) { content = "{}"; } else { content =
         * IOUtils.toString(i, c.getContentEncoding()); }
         */
        content = IOUtils.toString(i, c.getContentEncoding());
        rawcontent = content;
        prejson = new Date();
        j = new JSONObject(content);
        j.put("_success", true);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", c.getResponseCode());
        j.put("_available", available);
        j.put("_exception", "");
        j.put("_exceptionMessage", "");
        j.put("_content", content);
        postjson = new Date();
    } catch (JSONException ex) {
        if (ex.getMessage().contains("A JSONObject text must begin with")) {
            j = new JSONObject("{}");
            j.put("_success", true);
            j.put("_type", type.name());
            j.put("_url", url);
            j.put("_post", post);
            j.put("_http", 0);
            j.put("_available", available);
            j.put("_exception", "MalformedJSONData (HTTP " + responsecode + ")");
            j.put("_exceptionMessage", "");
            j.put("_content", rawcontent);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    } catch (NullPointerException ex) {
        com.gmt2001.Console.err.printStackTrace(ex);
    } catch (MalformedURLException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_available", available);
        j.put("_exception", "MalformedURLException");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");

        if (Quorrabot.enableDebugging) {
            com.gmt2001.Console.err.printStackTrace(ex);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    } catch (SocketTimeoutException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_available", available);
        j.put("_exception", "SocketTimeoutException");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");

        if (Quorrabot.enableDebugging) {
            com.gmt2001.Console.err.printStackTrace(ex);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    } catch (IOException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_available", available);
        j.put("_exception", "IOException");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");

        if (Quorrabot.enableDebugging) {
            com.gmt2001.Console.err.printStackTrace(ex);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    } catch (Exception ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_available", available);
        j.put("_exception", "Exception [" + ex.getClass().getName() + "]");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");

        if (Quorrabot.enableDebugging) {
            com.gmt2001.Console.err.printStackTrace(ex);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    }

    if (i != null) {
        try {
            i.close();
        } catch (IOException ex) {
            j.put("_success", false);
            j.put("_type", type.name());
            j.put("_url", url);
            j.put("_post", post);
            j.put("_http", 0);
            j.put("_available", available);
            j.put("_exception", "IOException");
            j.put("_exceptionMessage", ex.getMessage());
            j.put("_content", "");

            if (Quorrabot.enableDebugging) {
                com.gmt2001.Console.err.printStackTrace(ex);
            } else {
                com.gmt2001.Console.err.logStackTrace(ex);
            }
        }
    }

    if (Quorrabot.enableDebugging) {
        com.gmt2001.Console.out.println(">>>[DEBUG] LastFMAPI.GetData Timers "
                + (preconnect.getTime() - start.getTime()) + " " + (postconnect.getTime() - start.getTime())
                + " " + (prejson.getTime() - start.getTime()) + " " + (postjson.getTime() - start.getTime())
                + " " + start.toString() + " " + postjson.toString());
        com.gmt2001.Console.out.println(">>>[DEBUG] LastFMAPI.GetData Exception " + j.getString("_exception")
                + " " + j.getString("_exceptionMessage"));
        com.gmt2001.Console.out.println(">>>[DEBUG] LastFMAPI.GetData HTTP/Available " + j.getInt("_http") + "("
                + responsecode + ")/" + j.getInt("_available") + "(" + cl + ")");
        com.gmt2001.Console.out.println(">>>[DEBUG] LastFMAPI.GetData RawContent[0,100] "
                + j.getString("_content").substring(0, Math.min(100, j.getString("_content").length())));
    }

    return j;
}

From source file:org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest.java

public RestResponse httpsSendGet(String url, Map<String, String> headers) throws IOException {

    RestResponse restResponse = new RestResponse();
    URL obj = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
    // optional default is GET
    con.setRequestMethod("GET");
    // add request header
    if (headers != null) {
        for (Entry<String, String> header : headers.entrySet()) {
            String key = header.getKey();
            String value = header.getValue();
            con.setRequestProperty(key, value);
        }/*from   ww w  . j  ava 2 s.c  o m*/

    }

    int responseCode = con.getResponseCode();
    logger.debug("Send GET http request, url: {}", url);
    logger.debug("Response Code: {}", responseCode);

    StringBuffer response = new StringBuffer();
    try {
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
    } catch (Exception e) {
        logger.debug("response body is null");
    }

    String result;

    try {

        result = IOUtils.toString(con.getErrorStream());
        response.append(result);

    } catch (Exception e2) {
        // result = null;
    }
    logger.debug("Response body: {}", response);

    // print result

    restResponse.setErrorCode(responseCode);

    if (response != null) {
        restResponse.setResponse(response.toString());
    }

    restResponse.setErrorCode(responseCode);
    // restResponse.setResponse(result);
    Map<String, List<String>> headerFields = con.getHeaderFields();
    restResponse.setHeaderFields(headerFields);
    String responseMessage = con.getResponseMessage();
    restResponse.setResponseMessage(responseMessage);

    con.disconnect();

    return restResponse;
}

From source file:tangocard.sdk.service.ServiceProxy.java

/**
 * Post request.// w  w  w .j a  va 2s  . co  m
 *
 * @return true, if successful
 * @throws Exception the exception
 */
protected String postRequest() throws Exception {
    if (null == this._path) {
        throw new TangoCardSdkException("Member variable '_path' is null.");
    }

    String responseJsonEncoded = null;
    URL url = null;
    HttpsURLConnection connection = null;

    try {
        url = new URL(this._path);
    } catch (MalformedURLException e) {
        throw new TangoCardSdkException("MalformedURLException", e);
    }

    if (this.mapRequest()) {
        try {
            // connect to the server over HTTPS and submit the payload
            connection = (HttpsURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-length", String.valueOf(this._str_request_json.length()));
            connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");

            // open up the output stream of the connection
            DataOutputStream output = new DataOutputStream(connection.getOutputStream());
            output.write(this._str_request_json.getBytes());
        } catch (Exception e) {
            throw new TangoCardSdkException(String.format("Problems executing request: %s: '%s'",
                    e.getClass().toString(), e.getMessage()), e);
        }

        try {
            // now read the input stream until it is closed, line by line adding to the response
            InputStream inputstream = connection.getInputStream();
            InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
            BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
            StringBuffer response = new StringBuffer();
            String line = null;
            while ((line = bufferedreader.readLine()) != null) {
                response.append(line);
            }

            responseJsonEncoded = response.toString();
        } catch (Exception e) {
            throw new TangoCardSdkException(String.format("Problems reading response: %s: '%s'",
                    e.getClass().toString(), e.getMessage()), e);
        }
    }

    return responseJsonEncoded;
}

From source file:me.rojo8399.placeholderapi.impl.Metrics.java

/**
 * Sends the data to the bStats server./*from w  w w.ja v  a 2  s .c o m*/
 *
 * @param data
 *            The data to send.
 * @throws Exception
 *             If the request failed.
 */
private static void sendData(JsonObject data) throws Exception {
    Validate.notNull(data, "Data cannot be null");
    HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();

    // Compress the data to save bandwidth
    byte[] compressedData = compress(data.toString());

    // Add headers
    connection.setRequestMethod("POST");
    connection.addRequestProperty("Accept", "application/json");
    connection.addRequestProperty("Connection", "close");
    connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip
    // our
    // request
    connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
    connection.setRequestProperty("Content-Type", "application/json"); // We
    // send
    // our
    // data
    // in
    // JSON
    // format
    connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);

    // Send data
    connection.setDoOutput(true);
    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
    outputStream.write(compressedData);
    outputStream.flush();
    outputStream.close();

    connection.getInputStream().close(); // We don't care about the response
    // - Just send our data :)
}

From source file:org.wso2.carbon.identity.authenticator.wikid.WiKIDAuthenticator.java

/**
 * Send REST call//  w  w  w.  j  a  va 2  s. co  m
 */
private String sendRESTCall(String url, String urlParameters, String formParameters, String httpMethod) {
    String line;
    StringBuilder responseString = new StringBuilder();
    HttpsURLConnection connection = null;
    try {
        setHttpsClientCert(
                "/media/sf_SharedFoldersToVBox/is-connectors/wikid/wikid-authenticator/org.wso2.carbon.identity.authenticator/src/main/resources/localhostWiKID",
                "shakila");
        SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();

        URL wikidEP = new URL(url + urlParameters);
        connection = (HttpsURLConnection) wikidEP.openConnection();
        connection.setSSLSocketFactory(sslsocketfactory);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod(httpMethod);
        connection.setRequestProperty(WiKIDAuthenticatorConstants.HTTP_CONTENT_TYPE,
                WiKIDAuthenticatorConstants.HTTP_CONTENT_TYPE_XWFUE);
        if (httpMethod.toUpperCase().equals(WiKIDAuthenticatorConstants.HTTP_POST)) {
            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(),
                    WiKIDAuthenticatorConstants.CHARSET);
            writer.write(formParameters);
            writer.close();
        }
        if (connection.getResponseCode() == 200) {
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            while ((line = br.readLine()) != null) {
                responseString.append(line);
            }
            br.close();
        } else {
            return WiKIDAuthenticatorConstants.FAILED + WiKIDAuthenticatorConstants.REQUEST_FAILED;
        }
    } catch (ProtocolException e) {
        if (log.isDebugEnabled()) {
            log.debug(WiKIDAuthenticatorConstants.FAILED + e.getMessage());
        }
        return WiKIDAuthenticatorConstants.FAILED + e.getMessage();
    } catch (MalformedURLException e) {
        if (log.isDebugEnabled()) {
            log.debug(WiKIDAuthenticatorConstants.FAILED + e.getMessage());
        }
        return WiKIDAuthenticatorConstants.FAILED + e.getMessage();
    } catch (IOException e) {
        if (log.isDebugEnabled()) {
            log.debug(WiKIDAuthenticatorConstants.FAILED + e.getMessage());
        }
        return WiKIDAuthenticatorConstants.FAILED + e.getMessage();
    } finally {
        connection.disconnect();
    }
    return responseString.toString();
}

From source file:com.foundstone.certinstaller.CertInstallerActivity.java

/**
 * Tests the certificate chain by making a connection with or without the
 * proxy to the specified URL/* w w w.j a  va  2 s  . c  om*/
 * 
 * @param urlString
 * @param proxyIP
 * @param proxyPort
 */
private void testCertChain(final String urlString, final String proxyIP, final String proxyPort) {

    mCaCertInstalled = false;
    mSiteCertInstalled = false;

    if (TextUtils.isEmpty(urlString)) {
        Toast.makeText(getApplicationContext(), "URL is not set", Toast.LENGTH_SHORT).show();
        Log.d(TAG, "URL is not set");
        return;
    }
    pd = ProgressDialog.show(CertInstallerActivity.this, "Testing the cert chain", "", true, false, null);

    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {

            Log.d(TAG, "[+] Starting HTTPS request...");

            HttpsURLConnection urlConnection = null;

            try {
                Log.d(TAG, "[+] Set URL...");
                URL url = new URL("https://" + urlString);

                Log.d(TAG, "[+] Open Connection...");

                // The user could have ProxyDroid running
                if (!TextUtils.isEmpty(proxyIP) && !TextUtils.isEmpty(proxyPort)) {
                    Log.d(TAG, "[+] Using proxy " + proxyIP + ":" + proxyPort);
                    Proxy proxy = new Proxy(Type.HTTP,
                            new InetSocketAddress(proxyIP, Integer.parseInt(proxyPort)));
                    urlConnection = (HttpsURLConnection) url.openConnection(proxy);
                } else {
                    urlConnection = (HttpsURLConnection) url.openConnection();
                }
                urlConnection.setReadTimeout(15000);

                Log.d(TAG, "[+] Get the input stream...");
                InputStream in = urlConnection.getInputStream();
                Log.d(TAG, "[+] Create a buffered reader to read the response...");
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));

                final StringBuilder builder = new StringBuilder();

                String line = null;
                Log.d(TAG, "[+] Read all of the return....");
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                }

                mResult = builder.toString();

                Log.d(TAG, mResult);

                // If everything passed we set these both to true
                mCaCertInstalled = true;
                mSiteCertInstalled = true;

                // Catch when the CA doesn't exist
                // Error: javax.net.ssl.SSLHandshakeException:
                // java.security.cert.CertPathValidatorException: Trust
                // anchor for certification path not found
            } catch (SSLHandshakeException e) {

                e.printStackTrace();

                // Catch when the hostname does not verify
                // Line 224ish
                // http://source-android.frandroid.com/libcore/luni/src/main/java/libcore/net/http/HttpConnection.java
                // http://docs.oracle.com/javase/1.4.2/docs/api/javax/net/ssl/HostnameVerifier.html#method_detail
            } catch (IOException e) {

                // Found the CA cert installed but not the site cert
                mCaCertInstalled = true;
                e.printStackTrace();
            } catch (Exception e) {
                Log.d(TAG, "[-] Some other exception: " + e.getMessage());
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {

            pd.dismiss();
            if (mCaCertInstalled && !mSiteCertInstalled) {
                Log.d(TAG, Boolean.toString(mCaCertInstalled));
                Toast.makeText(getApplicationContext(), "Found the CA cert installed", Toast.LENGTH_SHORT)
                        .show();
                setCaTextInstalled();
                setSiteTextNotInstalled();
                setFullTextNotInstalled();
            } else if (mCaCertInstalled && mSiteCertInstalled) {
                Toast.makeText(getApplicationContext(), "Found the CA and Site certs installed",
                        Toast.LENGTH_SHORT).show();
                setCaTextInstalled();
                setSiteTextInstalled();
                setFullTextInstalled();
            } else {
                Toast.makeText(getApplicationContext(), "No Certificates were found installed",
                        Toast.LENGTH_SHORT).show();
                setCaTextNotInstalled();
                setSiteTextNotInstalled();
                setFullTextNotInstalled();
            }
            super.onPostExecute(result);

        }

    }.execute();

}

From source file:com.dao.ShopThread.java

private void pay(String payurl) {
    LogUtil.debugPrintf("----------->");
    try {/*from  w ww  .j  ava2 s.c om*/
        String postParams = getPayDynamicParams(payurl);
        HttpsURLConnection loginConn = getHttpSConn(payurl, "POST", Integer.toString(postParams.length()));
        if (null != this.cookies) {
            loginConn.addRequestProperty("Cookie", GenericUtil.cookieFormat(this.cookies));
        }

        LogUtil.debugPrintf("HEADER===" + loginConn.getRequestProperties());
        DataOutputStream wr = new DataOutputStream(loginConn.getOutputStream());
        wr.writeBytes(postParams);
        wr.flush();
        wr.close();
        int responseCode = loginConn.getResponseCode();
        LogUtil.debugPrintf("\nSending 'POST' request to URL : " + payurl);
        LogUtil.debugPrintf("Post parameters :" + postParams);
        LogUtil.debugPrintf("Response Code : " + responseCode);
        Map<String, List<String>> header = loginConn.getHeaderFields();
        LogUtil.debugPrintf("conn.getHeaderFields():" + header);
        BufferedReader in = new BufferedReader(new InputStreamReader(loginConn.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer(2000);
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        String payresponse = response.toString();
        LogUtil.debugPrintf("payresponse:" + payresponse);
        List<String> cookie = header.get("Set-Cookie");
        String loginInfo;
        if (responseCode != 302) {
            LogUtil.debugPrintf("----------->");
            loginInfo = "";
        } else {
            LogUtil.debugPrintf("?----------->");
            if (null != cookie && cookie.size() > 0) {
                LogUtil.debugPrintf("cookie====" + cookie);
                setCookies(cookie);
            }
            loginInfo = "?";
        }
        LogUtil.webPrintf(loginInfo);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.exoplatform.services.videocall.AuthService.java

public String authenticate(VideoCallModel videoCallModel, String profile_id) {
    VideoCallService videoCallService = new VideoCallService();
    if (videoCallModel == null) {
        caFile = videoCallService.getPemCertInputStream();
        p12File = videoCallService.getP12CertInputStream();
        videoCallModel = videoCallService.getVideoCallProfile();
    } else {//from w w  w. j  ava  2 s .  c o  m
        caFile = videoCallModel.getPemCert();
        p12File = videoCallModel.getP12Cert();
    }

    if (videoCallModel != null) {
        domain_id = videoCallModel.getDomainId();
        clientId = videoCallModel.getAuthId();
        clientSecret = videoCallModel.getAuthSecret();
        passphrase = videoCallModel.getCustomerCertificatePassphrase();
    }
    String responseContent = null;
    if (StringUtils.isEmpty(passphrase))
        return null;
    if (caFile == null || p12File == null)
        return null;

    try {
        String userId = ConversationState.getCurrent().getIdentity().getUserId();
        SSLContext ctx = SSLContext.getInstance("SSL");
        URL url = null;
        try {
            StringBuilder urlBuilder = new StringBuilder();
            urlBuilder.append(authUrl).append("?client_id=" + clientId).append("&client_secret=" + clientSecret)
                    .append("&uid=weemo" + userId)
                    .append("&identifier_client=" + URLEncoder.encode(domain_id, "UTF-8"))
                    .append("&id_profile=" + URLEncoder.encode(profile_id, "UTF-8"));
            url = new URL(urlBuilder.toString());
        } catch (MalformedURLException e) {
            if (LOG.isErrorEnabled()) {
                LOG.error("Could not create valid URL with base", e);
            }
        }
        HttpsURLConnection connection = null;
        try {
            connection = (HttpsURLConnection) url.openConnection();
        } catch (IOException e) {
            if (LOG.isErrorEnabled()) {
                LOG.error("Could not connect", e);
            }
        }
        TrustManager[] trustManagers = getTrustManagers(caFile, passphrase);
        KeyManager[] keyManagers = getKeyManagers("PKCS12", p12File, passphrase);

        ctx.init(keyManagers, trustManagers, new SecureRandom());
        try {
            connection.setSSLSocketFactory(ctx.getSocketFactory());
            connection.setRequestMethod("GET");
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        } catch (Exception e) {
            if (LOG.isErrorEnabled()) {
                LOG.error("Could not configure request for POST", e);
            }
        }

        try {
            connection.connect();
        } catch (IOException e) {
            if (LOG.isErrorEnabled()) {
                LOG.error("Could not connect to weemo", e);
            }
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder sbuilder = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sbuilder.append(line + "\n");
        }
        br.close();
        responseContent = sbuilder.toString();
        // Set new token key
        String tokenKey = "";
        if (!StringUtils.isEmpty(responseContent)) {
            JSONObject json = new JSONObject(responseContent);
            tokenKey = json.get("token").toString();
        } else {
            tokenKey = "";
        }
        videoCallService.setTokenKey(tokenKey);
    } catch (Exception ex) {
        LOG.error("Have problem during authenticating process.", ex);
        videoCallService.setTokenKey("");
    }
    return responseContent;
}

From source file:se.leap.bitmaskclient.ProviderAPI.java

/**
 * Executes an HTTP request expecting a JSON response.
 *
 * @param url//from   w  w  w.j  a  v  a 2 s.  c o  m
 * @param request_method
 * @param parameters
 * @return response from authentication server
 */
private JSONObject sendToServer(String url, String request_method, Map<String, String> parameters) {
    JSONObject json_response;
    HttpsURLConnection urlConnection = null;
    try {
        InputStream is = null;
        urlConnection = (HttpsURLConnection) new URL(url).openConnection();
        urlConnection.setRequestMethod(request_method);
        String locale = Locale.getDefault().getLanguage() + Locale.getDefault().getCountry();
        urlConnection.setRequestProperty("Accept-Language", locale);
        urlConnection.setChunkedStreamingMode(0);
        urlConnection.setSSLSocketFactory(getProviderSSLSocketFactory());

        DataOutputStream writer = new DataOutputStream(urlConnection.getOutputStream());
        writer.writeBytes(formatHttpParameters(parameters));
        writer.close();

        is = urlConnection.getInputStream();
        String plain_response = new Scanner(is).useDelimiter("\\A").next();
        json_response = new JSONObject(plain_response);
    } catch (ClientProtocolException e) {
        json_response = getErrorMessage(urlConnection);
        e.printStackTrace();
    } catch (IOException e) {
        json_response = getErrorMessage(urlConnection);
        e.printStackTrace();
    } catch (JSONException e) {
        json_response = getErrorMessage(urlConnection);
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        json_response = getErrorMessage(urlConnection);
        e.printStackTrace();
    } catch (KeyManagementException e) {
        json_response = getErrorMessage(urlConnection);
        e.printStackTrace();
    } catch (KeyStoreException e) {
        json_response = getErrorMessage(urlConnection);
        e.printStackTrace();
    } catch (CertificateException e) {
        json_response = getErrorMessage(urlConnection);
        e.printStackTrace();
    }

    return json_response;
}