Example usage for javax.net.ssl HttpsURLConnection setDoOutput

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

Introduction

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

Prototype

public void setDoOutput(boolean dooutput) 

Source Link

Document

Sets the value of the doOutput field for this URLConnection to the specified value.

Usage

From source file:com.yahoo.athenz.example.http.tls.client.HttpTLSClient.java

public static void main(String[] args) {

    // parse our command line to retrieve required input

    CommandLine cmd = parseCommandLine(args);

    final String url = cmd.getOptionValue("url");
    final String keyPath = cmd.getOptionValue("key");
    final String certPath = cmd.getOptionValue("cert");
    final String trustStorePath = cmd.getOptionValue("trustStorePath");
    final String trustStorePassword = cmd.getOptionValue("trustStorePassword");

    // we are going to setup our service private key and
    // certificate into a ssl context that we can use with
    // our http client

    try {/*from w ww.  ja  v a  2s  . com*/
        KeyRefresher keyRefresher = Utils.generateKeyRefresher(trustStorePath, trustStorePassword, certPath,
                keyPath);
        SSLContext sslContext = Utils.buildSSLContext(keyRefresher.getKeyManagerProxy(),
                keyRefresher.getTrustManagerProxy());

        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
        HttpsURLConnection con = (HttpsURLConnection) new URL(url).openConnection();
        con.setReadTimeout(15000);
        con.setDoOutput(true);
        con.connect();

        try (BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            System.out.println("Data output: " + sb.toString());
        }

    } catch (Exception ex) {
        System.out.println("Exception: " + ex.getMessage());
        ex.printStackTrace();
        System.exit(1);
    }
}

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);
        con.setRequestMethod("POST");
        OutputStreamWriter ow = new OutputStreamWriter(con.getOutputStream());
        ow.write(params);/*from   w  ww .ja  v  a 2 s  .  c  om*/
        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: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);//from  w  ww. j a v a  2s  .com
    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: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);//from   w  w w . j a  v  a2 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.liberty.android.fantastischmemo.downloader.google.FolderFactory.java

public static Folder createFolder(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);/*from ww w  .jav a 2  s  .co m*/
    conn.setDoOutput(true);
    conn.setRequestProperty("Authorization", "Bearer " + authToken);
    conn.setRequestProperty("Content-Type", "application/json");

    // Used to calculate the content length of the multi part
    String payload = "{\"title\":\"" + title + "\",\"mimeType\":\"application/vnd.google-apps.folder\"}";
    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(Folder.class, conn.getInputStream());
}

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);/*  w  w  w .  ja va2  s.  c  om*/
    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: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.  j  a 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.wso2.carbon.identity.application.authentication.endpoint.util.AuthContextAPIClient.java

/**
 * Send mutual ssl https post request and return data
 *
 * @param backendURL   URL of the service
 * @return Received data/*w  w w. jav a  2s  .  com*/
 * @throws IOException
 */
public static String getContextProperties(String backendURL) {
    InputStream inputStream = null;
    BufferedReader reader = null;
    String response = null;
    URL url = null;

    try {
        url = new URL(backendURL);
        HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();
        httpsURLConnection.setSSLSocketFactory(MutualSSLManager.getSslSocketFactory());
        httpsURLConnection.setDoOutput(true);
        httpsURLConnection.setDoInput(true);
        httpsURLConnection.setRequestMethod(HTTP_METHOD_GET);

        httpsURLConnection.setRequestProperty(MutualSSLManager.getUsernameHeaderName(),
                MutualSSLManager.getCarbonLogin());

        inputStream = httpsURLConnection.getInputStream();
        reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
        StringBuilder builder = new StringBuilder();
        String line;

        while (StringUtils.isNotEmpty(line = reader.readLine())) {
            builder.append(line);
        }
        response = builder.toString();
    } catch (IOException e) {
        log.error("Sending " + HTTP_METHOD_GET + " request to URL : " + url + "failed.", e);
    } finally {
        try {
            if (reader != null) {
                reader.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }

        } catch (IOException e) {
            log.error("Closing stream for " + url + " failed", e);
        }
    }
    return response;
}

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);//  w  w  w  .  j  a v  a2 s  .c o  m
        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:com.camel.trainreserve.JDKHttpsClient.java

private static HttpsURLConnection getConnection(URL url, String method, String ctype) throws IOException {
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setRequestMethod(method);/*  w ww.  j a va2s.c  o  m*/
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setRequestProperty("Accept", "text/xml,text/javascript,text/html");
    conn.setRequestProperty("User-Agent", "stargate");
    conn.setRequestProperty("Content-Type", ctype);
    return conn;
}