Example usage for javax.net.ssl HttpsURLConnection getOutputStream

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

Introduction

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

Prototype

public OutputStream getOutputStream() throws IOException 

Source Link

Document

Returns an output stream that writes to this connection.

Usage

From source file:com.bcmcgroup.flare.client.ClientUtil.java

/**
 * Sends an HTTPS POST request and returns the response
 *
 * @param conn    the HTTPS connection object
 * @param payload the payload for the POST request
 * @return the response from the remote server
 *
 *//*from w w w .j av  a2 s  .  c om*/
public static int sendPost(HttpsURLConnection conn, String payload) {
    OutputStream outputStream = null;
    DataOutputStream wr = null;
    InputStream is = null;
    int response = 0;
    logger.debug("Attempting HTTPS POST...");
    try {
        outputStream = conn.getOutputStream();
        wr = new DataOutputStream(outputStream);
        wr.write(payload.getBytes("UTF-8"));
        wr.flush();
        is = conn.getInputStream();
        response = conn.getResponseCode();
    } catch (IOException e) {
        logger.debug("IOException when attempting to send a post message. ");
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                logger.debug("IOException when attempting to close an input stream. ");
            }
        }
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                logger.debug("IOException when attempting to close an output stream. ");
            }
        }
        if (wr != null) {
            try {
                wr.close();
            } catch (IOException e) {
                logger.debug("IOException when attempting to close a data output stream. ");
            }
        }
    }
    logger.debug("HTTPS POST Response: " + response);
    return response;
}

From source file:com.bcmcgroup.flare.client.ClientUtil.java

/**
 * Sends an HTTPS POST request and returns the response in String format
 *
 * @param conn    the HTTPS connection object
 * @param payload the payload for the POST request
 * @return the response from the remote server in String format
 *
 *///from  w w  w  . ja  va  2s. c  o  m
public static String sendPostGetStringResponse(HttpsURLConnection conn, String payload) {
    OutputStream outputStream = null;
    DataOutputStream wr = null;
    InputStream is = null;
    String response = "";
    logger.debug("Attempting HTTPS POST");
    try {
        outputStream = conn.getOutputStream();
        wr = new DataOutputStream(outputStream);
        wr.write(payload.getBytes("UTF-8"));
        wr.flush();
        is = conn.getInputStream();
        response = IOUtils.toString(is, "UTF-8");
    } catch (IOException e) {
        logger.debug("IOException when attempting to send a post message. ");
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                logger.debug("IOException when attempting to close an input stream. ");
            }
        }
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                logger.debug("IOException when attempting to close an output stream. ");
            }
        }
        if (wr != null) {
            try {
                wr.close();
            } catch (IOException e) {
                logger.debug("IOException when attempting to close a data output stream. ");
            }
        }
    }
    return response;
}

From source file:org.wise.portal.presentation.web.filters.WISEAuthenticationProcessingFilter.java

/**
 * Check if the response is valid//www  .java  2  s  .c  om
 * @param reCaptchaPrivateKey the ReCaptcha private key
 * @param reCaptchaPublicKey the ReCaptcha public key
 * @param gRecaptchaResponse the response
 * @return whether the user answered the ReCaptcha successfully
 */
public static boolean checkReCaptchaResponse(String reCaptchaPrivateKey, String reCaptchaPublicKey,
        String gRecaptchaResponse) {

    boolean isValid = false;

    //check if the public key is valid in case the admin entered it wrong
    boolean reCaptchaKeyValid = isReCaptchaKeyValid(reCaptchaPublicKey, reCaptchaPrivateKey);

    if (reCaptchaKeyValid && reCaptchaPrivateKey != null && reCaptchaPublicKey != null
            && gRecaptchaResponse != null && !gRecaptchaResponse.equals("")) {

        try {

            // the url to verify the response
            URL verifyURL = new URL("https://www.google.com/recaptcha/api/siteverify");
            HttpsURLConnection connection = (HttpsURLConnection) verifyURL.openConnection();
            connection.setRequestMethod("POST");

            // set the params
            String postParams = "secret=" + reCaptchaPrivateKey + "&response=" + gRecaptchaResponse;

            // make the request to verify if the user answered the ReCaptcha successfully
            connection.setDoOutput(true);
            DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
            outputStream.writeBytes(postParams);
            outputStream.flush();
            outputStream.close();

            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(connection.getInputStream()));
            String inputLine = null;
            StringBuffer responseString = new StringBuffer();

            // read the response from the verify request
            while ((inputLine = bufferedReader.readLine()) != null) {
                responseString.append(inputLine);
            }

            bufferedReader.close();

            try {
                // create a JSON object from the response
                JSONObject responseObject = new JSONObject(responseString.toString());

                // get the value of the success field
                isValid = responseObject.getBoolean("success");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return isValid;
}

From source file:org.encuestame.core.util.SocialUtils.java

/**
 * Get Google Short Url./*from www  . j a v  a 2s.co  m*/
 * @return
 */
public static String getGoGl(final String urlPath, String key) {
    log.debug("getGoGl url " + urlPath);
    log.debug("getGoGl key " + key);
    String shortUrl = null;
    URL simpleURL = null;
    HttpsURLConnection url = null;
    BufferedInputStream bStream = null;
    StringBuffer resultString = new StringBuffer("");
    String inputString = "{\"longUrl\":\"" + urlPath + "\"}";
    log.debug("getGoGl inputString " + inputString);
    try {
        simpleURL = new URL("https://www.googleapis.com/urlshortener/v1/url?key=" + key);
        url = (HttpsURLConnection) simpleURL.openConnection();
        url.setDoOutput(true);
        url.setRequestProperty("content-type", "application/json");
        PrintWriter pw = new PrintWriter(url.getOutputStream());
        pw.print(inputString);
        pw.close();
    } catch (Exception ex) {
        log.error(ex);
        shortUrl = urlPath;
    }
    try {
        bStream = new BufferedInputStream(url.getInputStream());
        int i;
        while ((i = bStream.read()) >= 0) {
            resultString.append((char) i);
        }
        //  final Object jsonObject = JSONValue.parse(resultString.toString());
        //   final JSONObject o = (JSONObject) jsonObject;
        //   shortUrl = (String) o.get("id");
    } catch (Exception ex) {
        SocialUtils.log.error(ex);
        shortUrl = urlPath;
    }
    return shortUrl;
}

From source file:com.clearcenter.mobile_demo.mdRest.java

static public String Login(String host, String username, String password, String token) throws JSONException {
    if (password == null)
        Log.i(TAG, "Login by cookie, host: " + host + ", username: " + username);
    else/*from  w ww.  j  a  va2s  .  c o m*/
        Log.i(TAG, "Login by password, host: " + host + ", username: " + username);

    try {
        URL url = new URL("https://" + host + URL_LOGIN);

        HttpsURLConnection http = CreateConnection(url);

        if (password != null) {
            // Setup HTTPS POST request
            String urlParams = "username=" + URLEncoder.encode(username, "UTF-8") + "&password="
                    + URLEncoder.encode(password, "UTF-8") + "&submit=submit";

            http.setRequestMethod("POST");
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            http.setRequestProperty("Content-Length", Integer.toString(urlParams.getBytes().length));

            // Write request
            DataOutputStream outputStream = new DataOutputStream(http.getOutputStream());
            outputStream.writeBytes(urlParams);
            outputStream.flush();
            outputStream.close();
        } else {
            http.setRequestMethod("GET");
            http.setRequestProperty("Cookie", token);
        }

        final StringBuffer response = ProcessRequest(http);

        // Process response
        JSONObject json_data = null;
        try {
            Log.i(TAG, "response: " + response.toString());
            json_data = new JSONObject(response.toString());
        } catch (JSONException e) {
            Log.e(TAG, "JSONException", e);
            return "";
        }
        if (json_data.has("result")) {
            final String cookie = http.getHeaderField("Set-Cookie");
            Integer result = RESULT_UNKNOWN;
            try {
                result = Integer.valueOf(json_data.getString("result"));
            } catch (NumberFormatException e) {
            }

            Log.i(TAG, "result: " + result.toString() + ", cookie: " + cookie);

            if (result == RESULT_SUCCESS) {
                if (cookie != null)
                    return cookie;
                else
                    return token;
            }

            // All other results are failures...
            return "";
        }
    } catch (Exception e) {
        Log.e(TAG, "Exception", e);
    }

    Log.i(TAG, "Malformed result");
    return "";
}

From source file:org.openhab.binding.whistle.internal.WhistleBinding.java

protected static String getAuthToken(String username, String password) throws Exception {
    logger.debug("Using username: '{}' / password: '{}'", username, password);

    URL obj = new URL(APIROOT + "tokens.json");
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
    // add request headers and parameters
    con.setDoOutput(true);// w  w  w .  j  a  v  a 2  s. c  o m
    con.setRequestProperty("Content-Type", "application/json");
    con.setRequestProperty("User-Agent", "WhistleApp/102 (iPhone; iOS 7.0.4; Scale/2.00)");
    con.setRequestMethod("POST");
    String urlParameters = "{\"password\":\"" + password + "\",\"email\":\"" + username
            + "\",\"app_id\":\"com.whistle.WhistleApp\"}";
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();
    if (con.getResponseCode() != 200) {
        logger.error("Username / password combination didn't work. Failed to get AuthenticationToken");
        return null;
    }
    // Read the buffer
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String response = in.readLine();
    in.close();
    // Parse the data and return the token
    JsonObject jobj = new Gson().fromJson(response, JsonObject.class);
    return jobj.get("token").getAsString();
}

From source file:Main.IrcBot.java

public static void postGit(String pasteBinSnippet, PrintWriter out) {
    try {//from  w  ww.ja v  a  2 s  .c  o  m
        String url = "https://api.github.com/gists";
        URL obj = new URL(url);
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

        //add reuqest header
        JSONObject x = new JSONObject();
        JSONObject y = new JSONObject();
        JSONObject z = new JSONObject();
        z.put("content", pasteBinSnippet);
        y.put("index.txt", z);
        x.put("public", true);
        x.put("description", "LPBOT");
        x.put("files", y);
        con.setRequestMethod("POST");
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        String urlParameters = "public=true&description=LPBOT";

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(x.toString());
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + urlParameters);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        //print result
        JSONObject gitResponse = new JSONObject(response.toString());
        String newGitUrl = gitResponse.getString("html_url");

        if (newGitUrl.length() > 0) {
            out.println("PRIVMSG #learnprogramming :The paste on Git: " + newGitUrl);
        }
        System.out.println(newGitUrl);
    } catch (Exception p) {

    }
}

From source file:org.liberty.android.fantastischmemo.downloader.quizlet.lib.java

public static String[] getAccessTokens(final String[] requests) throws Exception {
    final String TAG = "getAccesTokens";
    String code = requests[0];/* w w  w. jav  a 2  s  .c  o m*/
    String clientIdAndSecret = QUIZLET_CLIENT_ID + ":" + QUIZLET_CLIENT_SECRET;
    String encodedClientIdAndSecret = Base64.encodeToString(clientIdAndSecret.getBytes(), 0);
    URL url1 = new URL("https://api.quizlet.com/oauth/token");
    HttpsURLConnection conn = (HttpsURLConnection) url1.openConnection();
    conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

    // Add the Basic Authorization item
    conn.addRequestProperty("Authorization", "Basic " + encodedClientIdAndSecret);

    conn.setRequestMethod("POST");
    conn.setDoInput(true);
    conn.setDoOutput(true);
    String payload = String.format("grant_type=%s&code=%s&redirect_uri=%s",
            URLEncoder.encode("authorization_code", "UTF-8"), URLEncoder.encode(code, "UTF-8"),
            URLEncoder.encode(Data.RedirectURI, "UTF-8"));
    OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
    out.write(payload);
    out.close();

    if (conn.getResponseCode() / 100 >= 3) {
        Log.e(TAG, "Http response code: " + conn.getResponseCode() + " response message: "
                + conn.getResponseMessage());
        JsonReader r = new JsonReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
        String error = "";
        r.beginObject();
        while (r.hasNext()) {
            error += r.nextName() + r.nextString() + "\r\n";
        }
        r.endObject();
        r.close();
        Log.e(TAG, "Error response for: " + url1 + " is " + error);
        throw new IOException("Response code: " + conn.getResponseCode());
    }

    JsonReader s = new JsonReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
    try {
        String accessToken = null;
        String userId = null;
        s.beginObject();
        while (s.hasNext()) {
            String name = s.nextName();
            if (name.equals("access_token")) {
                accessToken = s.nextString();
            } else if (name.equals("user_id")) {
                userId = s.nextString();
            } else {
                s.skipValue();
            }
        }
        s.endObject();
        s.close();
        return new String[] { accessToken, userId };
    } catch (Exception e) {
        // Throw out JSON exception. it is unlikely to happen
        throw new RuntimeException(e);
    } finally {
        conn.disconnect();
    }
}

From source file:com.hybris.mobile.data.WebServiceDataProvider.java

/**
 * Synchronous call for logging in/*w  w  w.  j  a v  a 2 s .c o  m*/
 * 
 * @param httpBody
 * @return The data from the server as a string, in almost all cases JSON
 * @throws MalformedURLException
 * @throws IOException
 * @throws JSONException
 */
public static String getLoginResponse(Bundle httpBody) throws MalformedURLException, IOException {
    String response = "";
    URL url = new URL(WebServiceAuthProvider.tokenURL());
    trustAllHosts();
    HttpsURLConnection connection = createSecureConnection(url);
    connection.setHostnameVerifier(DO_NOT_VERIFY);
    String authString = "mobile_android:secret";
    String authValue = "Basic " + Base64.encodeToString(authString.getBytes(), Base64.NO_WRAP);

    connection.setRequestMethod("POST");
    connection.setRequestProperty("Authorization", authValue);
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.connect();

    OutputStream os = new BufferedOutputStream(connection.getOutputStream());
    os.write(encodePostBody(httpBody).getBytes());
    os.flush();
    try {
        LoggingUtils.d(LOG_TAG, connection.toString());
        response = readFromStream(connection.getInputStream());
    } catch (MalformedURLException e) {
        LoggingUtils.e(LOG_TAG,
                "Error reading stream \"" + connection.getInputStream() + "\". " + e.getLocalizedMessage(),
                null);
    } catch (IOException e) {
        response = readFromStream(connection.getErrorStream());
    } finally {
        connection.disconnect();
    }

    return response;
}

From source file:com.raphfrk.craftproxyclient.net.auth.AuthManager.java

@SuppressWarnings("unchecked")
public static void authServer17(String hash) throws IOException {
    URL url;// w w  w . j a  v a  2s  .co  m
    String username;
    String accessToken;
    try {
        if (loginDetails == null) {
            throw new IOException("Not logged in");
        }

        try {
            username = URLEncoder.encode(getUsername(), "UTF-8");
            accessToken = URLEncoder.encode(getAccessToken(), "UTF-8");
            hash = URLEncoder.encode(hash, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new IOException("Username/password encoding error", e);
        }

        String urlString;
        urlString = sessionServer17;
        url = new URL(urlString);
    } catch (MalformedURLException e) {
        throw new IOException("Auth server URL error", e);
    }
    HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
    con.setDoOutput(true);
    con.setInstanceFollowRedirects(false);
    con.setReadTimeout(5000);
    con.setConnectTimeout(5000);
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/json");
    con.connect();

    JSONObject obj = new JSONObject();
    obj.put("accessToken", accessToken);
    obj.put("selectedProfile", loginDetails.get("selectedProfile"));
    obj.put("serverId", hash);
    BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(con.getOutputStream(), StandardCharsets.UTF_8));
    try {
        obj.writeJSONString(writer);
        writer.flush();
        writer.close();
    } catch (IOException e) {
        if (writer != null) {
            writer.close();
            con.disconnect();
            return;
        }
    }
    if (con.getResponseCode() != 200) {
        throw new IOException("Unable to verify username, please restart proxy");
    }
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
    try {
        String reply = reader.readLine();
        if (reply != null) {
            throw new IOException("Auth server replied (" + reply + ")");
        }
    } finally {
        reader.close();
        con.disconnect();
    }
}