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:org.openengsb.connector.facebook.internal.FacebookNotifier.java

private static String sendData(String httpsURL, String params) throws Exception {
    LOGGER.info("sending facebook-message");
    URL myurl = new URL(httpsURL);
    HttpsURLConnection con = (HttpsURLConnection) myurl.openConnection();
    if (params != null) {
        con.setDoOutput(true);//ww w.ja  v  a  2 s .  c  om
        con.setRequestMethod("POST");
        OutputStreamWriter ow = new OutputStreamWriter(con.getOutputStream());
        ow.write(params);
        ow.flush();
        ow.close();
    }
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));

    StringBuffer output = new StringBuffer();
    String inputLine;

    while ((inputLine = in.readLine()) != null) {
        output.append(inputLine);
        LOGGER.debug(inputLine);
    }
    in.close();
    LOGGER.info("facebook message has been sent");
    return output.toString();
}

From source file:com.ct855.util.HttpsClientUtil.java

public static String postUrl(String url, Map<String, String> params)
        throws IOException, NoSuchAlgorithmException, KeyManagementException, NoSuchProviderException {
    //SSLContext??
    TrustManager[] trustAllCerts = new TrustManager[] { new MyX509TrustManager() };
    SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
    sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

    //SSLContextSSLSocketFactory
    SSLSocketFactory ssf = sslContext.getSocketFactory();
    String data = "";
    for (String key : params.keySet()) {
        data += "&" + URLEncoder.encode(key, "UTF-8") + "=" + URLEncoder.encode(params.get(key), "UTF-8");
    }/*w  ww . ja  v  a2s.co  m*/
    data = data.substring(1);

    System.out.println("postUrl=>data:" + data);
    URL aURL = new java.net.URL(url);
    HttpsURLConnection aConnection = (HttpsURLConnection) aURL.openConnection();
    aConnection.setSSLSocketFactory(ssf);
    aConnection.setDoOutput(true);
    aConnection.setDoInput(true);
    aConnection.setRequestMethod("POST");
    OutputStreamWriter streamToAuthorize = new java.io.OutputStreamWriter(aConnection.getOutputStream());
    streamToAuthorize.write(data);
    streamToAuthorize.flush();
    streamToAuthorize.close();
    InputStream resultStream = aConnection.getInputStream();
    BufferedReader aReader = new java.io.BufferedReader(new java.io.InputStreamReader(resultStream));
    StringBuffer aResponse = new StringBuffer();
    String aLine = aReader.readLine();
    while (aLine != null) {
        aResponse.append(aLine + "\n");
        aLine = aReader.readLine();
    }
    resultStream.close();
    return aResponse.toString();
}

From source file:org.liberty.android.fantastischmemo.downloader.google.WorksheetFactory.java

public static Worksheet createWorksheet(Spreadsheet spreadsheet, String title, int row, int col,
        String authToken) throws Exception {
    URL url = new URL("https://spreadsheets.google.com/feeds/worksheets/" + spreadsheet.getId()
            + "/private/full?access_token=" + authToken);

    String payload = "<entry xmlns=\"http://www.w3.org/2005/Atom\""
            + " xmlns:gs=\"http://schemas.google.com/spreadsheets/2006\">" + "<title>"
            + URLEncoder.encode(title, "UTF-8") + "</title>" + "<gs:rowCount>" + row + "</gs:rowCount>"
            + "<gs:colCount>" + col + "</gs:colCount>" + "</entry>";

    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setDoInput(true);//from w  w  w.  j  a  v a 2  s.c o  m
    conn.setDoOutput(true);
    conn.addRequestProperty("Content-Type", "application/atom+xml");
    conn.addRequestProperty("Content-Length", "" + payload.getBytes("UTF-8").length);
    OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
    out.write(payload);
    out.close();

    if (conn.getResponseCode() / 100 >= 3) {
        String s = new String(IOUtils.toByteArray(conn.getErrorStream()));
        throw new Exception(s);
    }

    List<Worksheet> worksheets = getWorksheets(spreadsheet, authToken);
    for (Worksheet worksheet : worksheets) {
        if (title.equals(worksheet.getTitle())) {
            return worksheet;
        }
    }
    throw new IllegalStateException("Worksheet lookup failed. Worksheet is not created properly.");
}

From source file:org.liberty.android.fantastischmemo.downloader.google.CellsFactory.java

public static void uploadCells(Spreadsheet spreadsheet, Worksheet worksheet, Cells cells, String authToken)
        throws IOException {
    URL url = new URL("https://spreadsheets.google.com/feeds/cells/" + spreadsheet.getId() + "/"
            + worksheet.getId() + "/private/full/batch?access_token=" + authToken);
    String urlPrefix = "https://spreadsheets.google.com/feeds/cells/" + spreadsheet.getId() + "/"
            + worksheet.getId() + "/private/full";

    for (int r = 0; r < cells.getRowCounts(); r += MAX_BATCH_SIZE) {
        int upBound = Math.min(r + MAX_BATCH_SIZE, cells.getRowCounts());

        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoInput(true);/*from   w  w w. j av  a 2 s  . c om*/
        conn.setDoOutput(true);
        conn.addRequestProperty("Content-Type", "application/atom+xml");
        //conn.addRequestProperty("Content-Length", "" + payload.length());
        conn.addRequestProperty("If-Match", "*");
        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());

        StringBuilder head = new StringBuilder();
        head.append("<?xml version='1.0' encoding='UTF-8'?>");
        head.append(
                "<feed xmlns=\"http://www.w3.org/2005/Atom\" xmlns:batch=\"http://schemas.google.com/gdata/batch\" xmlns:gs=\"http://schemas.google.com/spreadsheets/2006\">");
        head.append("<id>" + urlPrefix + "</id>");

        out.write(head.toString());

        for (int i = r; i < upBound; i++) {
            List<String> row = cells.getRow(i);
            for (int j = 0; j < row.size(); j++) {
                out.write(getEntryToRequesetString(urlPrefix, i + 1, j + 1, row.get(j)));
            }
        }
        out.write("</feed>");

        out.close();
        if (conn.getResponseCode() / 100 >= 3) {
            String s = new String(IOUtils.toByteArray(conn.getErrorStream()));
            throw new IOException(s);
        }
    }
}

From source file:org.liberty.android.fantastischmemo.downloader.google.FolderFactory.java

public static void addDocumentToFolder(Document document, Folder folder, String authToken)
        throws XmlPullParserException, IOException {
    URL url = new URL("https://www.googleapis.com/drive/v2/files/" + document.getId() + "/parents");

    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setDoInput(true);//w  w  w.  j a  v  a  2 s  .  c o m
    conn.setDoOutput(true);
    conn.setRequestProperty("Authorization", "Bearer " + authToken);
    conn.setRequestProperty("Content-Type", "application/json");

    String payload = "{\"id\":\"" + folder.getId() + "\"}";
    conn.setRequestProperty("Content-Length", "" + payload.length());

    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(conn.getOutputStream());
    outputStreamWriter.write(payload);
    outputStreamWriter.close();

    if (conn.getResponseCode() / 100 >= 3) {
        String s = new String(IOUtils.toByteArray(conn.getErrorStream()));
        throw new RuntimeException(s);
    }
}

From source file:org.openadaptor.util.PropertiesPoster.java

/**
 * Utility method which will attempt to POST the supplied properties information to the supplied URL.
 * //from w w  w . j  a v a  2s . com
 * This method currently contains an all trusting trust manager for use with https. This will be replaced with a more
 * secure trust manager which will use a cert store.
 * 
 * @param registrationURL
 * @param properties
 * @throws Exception
 */
protected static void syncPostHttp(String registrationURL, Properties properties) throws Exception {

    URL url = new URL(registrationURL);
    String postData = generatePOSTData(properties);
    log.debug("Protocol: " + url.getProtocol());
    if (url.getProtocol().equals("https")) {

        // https connection

        // TODO: Replace this all trusting manager with one that uses a cert store
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }
        } };

        // Install the all-trusting trust manager
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());

        HttpsURLConnection secureConnection = null;
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        secureConnection = (HttpsURLConnection) url.openConnection();
        secureConnection.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(secureConnection.getOutputStream());
        writer.write(postData);
        writer.flush();
        int responseCode = secureConnection.getResponseCode();
        if (HttpsURLConnection.HTTP_OK != responseCode) {
            log.error("\nFailed to register. Response Code " + responseCode + "\nResponse message:"
                    + secureConnection.getResponseMessage() + "\nRegistration URL: " + registrationURL
                    + "\nData: " + generateString(properties));
        }
        BufferedReader br = new BufferedReader(new InputStreamReader(secureConnection.getInputStream()));
        String line;
        while ((line = br.readLine()) != null) {
            log.debug("Returned data: " + line);
        }
        writer.close();
        br.close();
    } else {

        // Normal http connection
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
        writer.write(postData);
        writer.flush();
        int responseCode = connection.getResponseCode();
        if (HttpURLConnection.HTTP_OK != responseCode) {
            log.error("\nFailed to register. Response Code " + responseCode + "\nResponse message:"
                    + connection.getResponseMessage() + "\nRegistration URL: " + registrationURL + "\nData: "
                    + generateString(properties));
        }
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        while ((line = br.readLine()) != null) {
            log.debug("Returned data: " + line);
        }
        writer.close();
        br.close();
    }
}

From source file:org.liberty.android.fantastischmemo.downloader.google.DocumentFactory.java

public static Document createSpreadsheet(String title, String authToken)
        throws XmlPullParserException, IOException {
    URL url = new URL("https://www.googleapis.com/drive/v2/files");

    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setDoInput(true);//  w  w w .j  ava  2 s  .  co  m
    conn.setDoOutput(true);
    conn.setRequestProperty("Authorization", "Bearer " + authToken);
    conn.setRequestProperty("Content-Type", "application/json");

    String payload = "{\"title\":\"" + title + "\",\"mimeType\":\"application/vnd.google-apps.spreadsheet\"}";
    conn.setRequestProperty("Content-Length", "" + payload.length());

    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(conn.getOutputStream());
    outputStreamWriter.write(payload);
    outputStreamWriter.close();

    if (conn.getResponseCode() / 100 >= 3) {
        String s = new String(IOUtils.toByteArray(conn.getErrorStream()));
        throw new RuntimeException(s);
    }

    return EntryFactory.getEntryFromDriveApi(Document.class, conn.getInputStream());
}

From source file:com.coinprism.model.APIClient.java

private static String executeHttpPost(String url, String body) throws IOException, APIException {
    URL target = new URL(url);
    HttpsURLConnection connection = (HttpsURLConnection) target.openConnection();

    connection.setRequestMethod("POST");
    connection.setRequestProperty("User-Agent", userAgent);
    connection.setRequestProperty("Content-Type", "application/json");

    OutputStream output = null;//from  ww  w  .j a va  2s  .  c o m
    try {
        output = connection.getOutputStream();
        output.write(body.getBytes("UTF-8"));
    } finally {
        if (output != null)
            output.close();
    }

    return getHttpResponse(connection);
}

From source file:org.kuali.mobility.push.service.send.AndroidSendService.java

/**
 * Writes the data over the connection/*  w  w  w .  j  av a2  s. c  o  m*/
 * @param conn
 * @param data
 * @return
 * @throws java.net.MalformedURLException
 * @throws java.io.IOException
 */
private static String sendToGCM(HttpsURLConnection conn, String data) throws IOException {
    byte[] dataBytes = data.getBytes();
    conn.setFixedLengthStreamingMode(dataBytes.length);
    OutputStream out = null;
    String response = null;
    try {
        out = conn.getOutputStream();
        out.write(dataBytes);
        out.flush();
        response = readResponse(conn);

    } catch (IOException e) {
        LOG.warn("Exception while trying to write data to GCM", e);
    } finally {
        IOUtils.closeQuietly(out);
        conn.disconnect();
    }
    return response;
}

From source file:ro.fortsoft.matilda.util.RecaptchaUtils.java

public static boolean verify(String recaptchaResponse, String secret) {
    if (StringUtils.isNullOrEmpty(recaptchaResponse)) {
        return false;
    }/*from   w w w. java 2 s  .com*/

    boolean result = false;
    try {
        URL url = new URL("https://www.google.com/recaptcha/api/siteverify");
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();

        // add request header
        connection.setRequestMethod("POST");
        connection.setRequestProperty("User-Agent", "Mozilla/5.0");
        connection.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        String postParams = "secret=" + secret + "&response=" + recaptchaResponse;
        //            log.debug("Post parameters '{}'", postParams);

        // send post request
        connection.setDoOutput(true);
        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
        outputStream.writeBytes(postParams);
        outputStream.flush();
        outputStream.close();

        int responseCode = connection.getResponseCode();
        log.debug("Response code '{}'", responseCode);

        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder response = new StringBuilder();

        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();

        // print result
        log.debug("Response '{}'", response.toString());

        // parse JSON response and return 'success' value
        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = mapper.readTree(response.toString());
        JsonNode nameNode = rootNode.path("success");

        result = nameNode.asBoolean();
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }

    return result;
}