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:net.mms_projects.copy_it.server.push.android.GCMRunnable.java

public void run() {
    try {/* ww w. jav a  2s .  co  m*/
        URL url = new URL(GCM_URL);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod(POST);
        conn.setRequestProperty(CONTENT_TYPE, Page.ContentTypes.JSON_TYPE);
        conn.setRequestProperty(AUTHORIZATION, KEY);
        final String output_json = full.toString();
        System.err.println("Input json: " + output_json);
        conn.setRequestProperty(CONTENT_LENGTH, String.valueOf(output_json.length()));
        conn.setDoOutput(true);
        conn.setDoInput(true);
        DataOutputStream outputstream = new DataOutputStream(conn.getOutputStream());
        outputstream.writeBytes(output_json);
        outputstream.close();
        DataInputStream input = new DataInputStream(conn.getInputStream());
        StringBuilder builder = new StringBuilder(input.available());
        for (int c = input.read(); c != -1; c = input.read())
            builder.append((char) c);
        input.close();
        output = new JSONObject(builder.toString());
        System.err.println("Output json: " + output.toString());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:Main.java

public static String executeHttpsPost(String url, String data, InputStream key) {
    HttpsURLConnection localHttpsURLConnection = null;
    try {/*w  w  w. jav a2  s  .com*/
        URL localURL = new URL(url);
        localHttpsURLConnection = (HttpsURLConnection) localURL.openConnection();
        localHttpsURLConnection.setRequestMethod("POST");
        localHttpsURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        localHttpsURLConnection.setRequestProperty("Content-Length",
                "" + Integer.toString(data.getBytes().length));
        localHttpsURLConnection.setRequestProperty("Content-Language", "en-US");

        localHttpsURLConnection.setUseCaches(false);
        localHttpsURLConnection.setDoInput(true);
        localHttpsURLConnection.setDoOutput(true);

        localHttpsURLConnection.connect();
        Certificate[] arrayOfCertificate = localHttpsURLConnection.getServerCertificates();

        byte[] arrayOfByte1 = new byte[294];
        DataInputStream localDataInputStream = new DataInputStream(key);
        localDataInputStream.readFully(arrayOfByte1);
        localDataInputStream.close();

        Certificate localCertificate = arrayOfCertificate[0];
        PublicKey localPublicKey = localCertificate.getPublicKey();
        byte[] arrayOfByte2 = localPublicKey.getEncoded();

        for (int i = 0; i < arrayOfByte2.length; i++) {
            if (arrayOfByte2[i] != arrayOfByte1[i])
                throw new RuntimeException("Public key mismatch");
        }

        DataOutputStream localDataOutputStream = new DataOutputStream(
                localHttpsURLConnection.getOutputStream());
        localDataOutputStream.writeBytes(data);
        localDataOutputStream.flush();
        localDataOutputStream.close();

        InputStream localInputStream = localHttpsURLConnection.getInputStream();
        BufferedReader localBufferedReader = new BufferedReader(new InputStreamReader(localInputStream));

        StringBuffer localStringBuffer = new StringBuffer();
        String str1;
        while ((str1 = localBufferedReader.readLine()) != null) {
            localStringBuffer.append(str1);
            localStringBuffer.append('\r');
        }
        localBufferedReader.close();

        return localStringBuffer.toString();
    } catch (Exception localException) {
        byte[] arrayOfByte1;
        localException.printStackTrace();
        return null;
    } finally {
        if (localHttpsURLConnection != null)
            localHttpsURLConnection.disconnect();
    }
}

From source file:org.openmrs.module.rheashradapter.util.GenerateORU_R01Alert.java

public String callQueryFacility(String msg, Encounter e)
        throws IOException, TransformerFactoryConfigurationError, TransformerException {

    Cohort singlePatientCohort = new Cohort();
    singlePatientCohort.addMember(e.getPatient().getId());

    Map<Integer, String> patientIdentifierMap = Context.getPatientSetService()
            .getPatientIdentifierStringsByType(singlePatientCohort, Context.getPatientService()
                    .getPatientIdentifierTypeByName(RHEAHL7Constants.IDENTIFIER_TYPE));

    // Setup connection
    String id = patientIdentifierMap.get(patientIdentifierMap.keySet().iterator().next());
    URL url = new URL(hostname + "/ws/rest/v1/alerts");
    System.out.println("full url " + url);
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setDoOutput(true);/*from   w ww .  ja va2 s. c om*/
    conn.setRequestMethod("POST");
    conn.setDoInput(true);

    // This is important to get the connection to use our trusted
    // certificate
    conn.setSSLSocketFactory(sslFactory);

    addHTTPBasicAuthProperty(conn);
    // conn.setConnectTimeout(timeOut);
    OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
    log.error("body" + msg);
    out.write(msg);
    out.close();
    conn.connect();
    String headerValue = conn.getHeaderField("http.status");

    // Test response code
    if (conn.getResponseCode() != 200) {
        throw new IOException(conn.getResponseMessage());
    }

    String result = convertInputStreamToString(conn.getInputStream());
    conn.disconnect();

    return result;
}

From source file:com.glaf.core.util.http.HttpUtils.java

/**
 * ?https?//from  www . j  ava 2 s  .c o  m
 * 
 * @param requestUrl
 *            ?
 * @param method
 *            ?GET?POST
 * @param content
 *            ???
 * @return
 */
public static String doRequest(String requestUrl, String method, String content, boolean isSSL) {
    log.debug("requestUrl:" + requestUrl);
    HttpsURLConnection conn = null;
    InputStream inputStream = null;
    BufferedReader bufferedReader = null;
    InputStreamReader inputStreamReader = null;
    StringBuffer buffer = new StringBuffer();
    try {
        URL url = new URL(requestUrl);
        conn = (HttpsURLConnection) url.openConnection();
        if (isSSL) {
            // SSLContext??
            TrustManager[] tm = { new MyX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // SSLContextSSLSocketFactory
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            conn.setSSLSocketFactory(ssf);
        }
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        // ?GET/POST
        conn.setRequestMethod(method);
        if ("GET".equalsIgnoreCase(method)) {
            conn.connect();
        }

        // ????
        if (StringUtils.isNotEmpty(content)) {
            OutputStream outputStream = conn.getOutputStream();
            // ????
            outputStream.write(content.getBytes("UTF-8"));
            outputStream.flush();
            outputStream.close();
        }

        // ???
        inputStream = conn.getInputStream();
        inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
        bufferedReader = new BufferedReader(inputStreamReader);

        String str = null;
        while ((str = bufferedReader.readLine()) != null) {
            buffer.append(str);
        }

        log.debug("response:" + buffer.toString());

    } catch (ConnectException ce) {
        ce.printStackTrace();
        log.error(" http server connection timed out.");
    } catch (Exception ex) {
        ex.printStackTrace();
        log.error("http request error:{}", ex);
    } finally {
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(bufferedReader);
        IOUtils.closeQuietly(inputStreamReader);
        if (conn != null) {
            conn.disconnect();
        }
    }
    return buffer.toString();
}

From source file:org.talend.components.marketo.runtime.client.MarketoBulkExecClient.java

public BulkImportResult executePostFileRequest(Class<?> resultClass, String filePath) throws MarketoException {
    String boundary = "Talend_tMarketoBulkExec_" + String.valueOf(System.currentTimeMillis());
    try {//from  w ww.  j  a  v  a2  s  .c  o m
        URL url = new URL(current_uri.toString());
        HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();
        urlConn.setRequestMethod("POST");
        urlConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        urlConn.setRequestProperty("accept", "text/json");
        urlConn.setDoOutput(true);
        String requestBody = buildRequest(filePath); // build the request body
        PrintWriter wr = new PrintWriter(new OutputStreamWriter(urlConn.getOutputStream()));
        wr.append("--" + boundary + "\r\n");
        wr.append("Content-Disposition: form-data; name=\"file\";filename=\"" + filePath + "\";\r\n");
        wr.append("Content-type: text/plain; charset=\"utf-8\"\r\n");
        wr.append("Content-Transfer-Encoding: text/plain\r\n");
        wr.append("MIME-Version: 1.0\r\n");
        wr.append("\r\n");
        wr.append(requestBody);
        wr.append("\r\n");
        wr.append("--" + boundary);
        wr.flush();
        wr.close();
        int responseCode = urlConn.getResponseCode();
        if (responseCode == 200) {
            InputStream inStream = urlConn.getInputStream();
            InputStreamReader reader = new InputStreamReader(inStream);
            Gson gson = new Gson();
            return (BulkImportResult) gson.fromJson(reader, resultClass);
        } else {
            LOG.error("POST request failed: {}", responseCode);
            throw new MarketoException(REST, responseCode,
                    "Request failed! Please check your request setting!");
        }
    } catch (IOException e) {
        LOG.error("POST request failed: {}", e.getMessage());
        throw new MarketoException(REST, e.getMessage());
    }
}

From source file:hudson.plugins.boundary.Boundary.java

public void sendEvent(AbstractBuild<?, ?> build, BuildListener listener) throws IOException {
    final HashMap<String, Object> event = new HashMap<String, Object>();
    event.put("fingerprintFields", Arrays.asList("build name"));

    final Map<String, String> source = new HashMap<String, String>();
    String hostname = "localhost";

    try {// w w  w  .j  a  v a  2  s.  com
        hostname = java.net.InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException e) {
        listener.getLogger().println("host lookup exception: " + e);
    }

    source.put("ref", hostname);
    source.put("type", "jenkins");
    event.put("source", source);

    final Map<String, String> properties = new HashMap<String, String>();
    properties.put("build status", build.getResult().toString());
    properties.put("build number", build.getDisplayName());
    properties.put("build name", build.getProject().getName());
    event.put("properties", properties);

    event.put("title",
            String.format("Jenkins Build Job - %s - %s", build.getProject().getName(), build.getDisplayName()));

    if (Result.SUCCESS.equals(build.getResult())) {
        event.put("severity", "INFO");
        event.put("status", "CLOSED");
    } else {
        event.put("severity", "WARN");
        event.put("status", "OPEN");
    }

    final String url = String.format("https://api.boundary.com/%s/events", this.id);
    final HttpsURLConnection conn = (HttpsURLConnection) new URL(url).openConnection();
    conn.setConnectTimeout(30000);
    conn.setReadTimeout(30000);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json");
    final String authHeader = "Basic " + new String(Base64.encodeBase64((token + ":").getBytes(), false));
    conn.setRequestProperty("Authorization", authHeader);
    conn.setDoInput(true);
    conn.setDoOutput(true);

    InputStream is = null;
    OutputStream os = null;
    try {
        os = conn.getOutputStream();
        OBJECT_MAPPER.writeValue(os, event);
        os.flush();
        is = conn.getInputStream();
    } finally {
        close(is);
        close(os);
    }

    final int responseCode = conn.getResponseCode();
    if (responseCode != HttpURLConnection.HTTP_CREATED) {
        listener.getLogger().println("Invalid HTTP response code from Boundary API: " + responseCode);
    } else {
        String location = conn.getHeaderField("Location");
        if (location.startsWith("http:")) {
            location = "https" + location.substring(4);
        }
        listener.getLogger().println("Created Boundary Event: " + location);
    }
}

From source file:net.minder.KnoxWebHdfsJavaClientExamplesTest.java

@Test
public void putGetFileExample() throws Exception {
    HttpsURLConnection connection;
    String redirect;//www.  j  av  a2s .  co  m
    InputStream input;
    OutputStream output;

    String data = UUID.randomUUID().toString();

    connection = createHttpUrlConnection(WEBHDFS_URL + "/tmp/" + data + "/?op=CREATE");
    connection.setRequestMethod("PUT");
    assertThat(connection.getResponseCode(), is(307));
    redirect = connection.getHeaderField("Location");
    connection.disconnect();

    connection = createHttpUrlConnection(redirect);
    connection.setRequestMethod("PUT");
    connection.setDoOutput(true);
    output = connection.getOutputStream();
    IOUtils.write(data.getBytes(), output);
    output.close();
    connection.disconnect();
    assertThat(connection.getResponseCode(), is(201));

    connection = createHttpUrlConnection(WEBHDFS_URL + "/tmp/" + data + "/?op=OPEN");
    assertThat(connection.getResponseCode(), is(307));
    redirect = connection.getHeaderField("Location");
    connection.disconnect();

    connection = createHttpUrlConnection(redirect);
    input = connection.getInputStream();
    assertThat(IOUtils.toString(input), is(data));
    input.close();
    connection.disconnect();

}

From source file:edu.hackathon.perseus.core.httpSpeedTest.java

public void sendPost() throws Exception {

    String url = "https://selfsolve.apple.com/wcResults.do";
    URL obj = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

    //add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

    String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";

    // Send post request
    con.setDoOutput(true);//  w  w w  . ja v  a2  s .c o m
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    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
    System.out.println(response.toString());
}

From source file:org.wso2.carbon.appmgt.sample.deployer.http.HttpHandler.java

/**
 * This method is used to do a https post request
 *
 * @param url         request url//from   w w w .j a va  2  s  . c  o  m
 * @param payload     Content of the post request
 * @param sessionId   sessionId for authentication
 * @param contentType content type of the post request
 * @return response
 * @throws java.io.IOException - Throws this when failed to fulfill a https post request
 */
public String doPostHttps(String url, String payload, String sessionId, String contentType) throws IOException {
    URL obj = new URL(url);

    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
    //add reuqest header
    con.setRequestMethod("POST");
    if (!sessionId.equals("")) {
        con.setRequestProperty("Cookie", "JSESSIONID=" + sessionId);
    }
    if (!contentType.equals("")) {
        con.setRequestProperty("Content-Type", contentType);
    }
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(payload);
    wr.flush();
    wr.close();
    int responseCode = con.getResponseCode();
    if (responseCode == 200) {
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        if (sessionId.equals("")) {
            String session_id = response.substring((response.lastIndexOf(":") + 3),
                    (response.lastIndexOf("}") - 2));
            return session_id;
        } else if (sessionId.equals("header")) {
            return con.getHeaderField("Set-Cookie");
        }

        return response.toString();
    }
    return null;
}

From source file:com.alvexcore.share.ShareExtensionRegistry.java

public ExtensionUpdateInfo checkForUpdates(String extensionId, String shareId, Map<String, String> shareHashes,
        String shareVersion, String repoId, Map<String, String> repoHashes, String repoVersion,
        String licenseId) throws Exception {
    // search for extension
    DocumentBuilderFactory xmlFact = DocumentBuilderFactory.newInstance();
    xmlFact.setNamespaceAware(true);/*w  w  w .  java  2s .c om*/
    xmlBuilder = xmlFact.newDocumentBuilder();

    // build query
    Document queryXML = xmlBuilder.newDocument();
    Element rootElement = queryXML.createElement("extension");
    queryXML.appendChild(rootElement);
    Element el = queryXML.createElement("license-id");
    el.appendChild(queryXML.createTextNode(licenseId));
    rootElement.appendChild(el);
    el = queryXML.createElement("id");
    el.appendChild(queryXML.createTextNode(extensionId));
    rootElement.appendChild(el);
    el = queryXML.createElement("share-version");
    el.appendChild(queryXML.createTextNode(shareVersion));
    rootElement.appendChild(el);
    el = queryXML.createElement("repo-version");
    el.appendChild(queryXML.createTextNode(repoVersion));
    rootElement.appendChild(el);
    el = queryXML.createElement("share-id");
    el.appendChild(queryXML.createTextNode(shareId));
    rootElement.appendChild(el);
    el = queryXML.createElement("repo-id");
    el.appendChild(queryXML.createTextNode(repoId));
    rootElement.appendChild(el);
    el = queryXML.createElement("share-files");
    rootElement.appendChild(el);
    for (String fileName : shareHashes.keySet()) {
        Element fileElem = queryXML.createElement("file");
        fileElem.setAttribute("md5hash", shareHashes.get(fileName));
        fileElem.appendChild(queryXML.createTextNode(fileName));
        el.appendChild(fileElem);
    }
    el = queryXML.createElement("repo-files");
    rootElement.appendChild(el);
    for (String fileName : repoHashes.keySet()) {
        Element fileElem = queryXML.createElement("file");
        fileElem.setAttribute("md5hash", repoHashes.get(fileName));
        fileElem.appendChild(queryXML.createTextNode(fileName));
        el.appendChild(fileElem);
    }
    // query server
    try {
        URL url = new URL(
                "https://update.alvexhq.com:443/alfresco/s/api/alvex/extension/" + extensionId + "/update");
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        // disable host verification
        conn.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        });
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.connect();
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        TransformerFactory.newInstance().newTransformer().transform(new DOMSource(queryXML),
                new StreamResult(wr));
        wr.close();
        // get response
        Document responseXML = xmlBuilder.parse(conn.getInputStream());
        XPath xpath = XPathFactory.newInstance().newXPath();

        // get version
        String repoLatestVersion = ((Node) xpath.evaluate("/extension/repo-version/text()", responseXML,
                XPathConstants.NODE)).getNodeValue();
        String shareLatestVersion = ((Node) xpath.evaluate("/extension/share-version/text()", responseXML,
                XPathConstants.NODE)).getNodeValue();
        NodeList nl = (NodeList) xpath.evaluate("/extension/repo-files/file", responseXML,
                XPathConstants.NODESET);
        Map<String, Boolean> repoFiles = new HashMap<String, Boolean>(nl.getLength());
        for (int i = 0; i < nl.getLength(); i++)
            repoFiles.put(nl.item(i).getTextContent(),
                    "ok".equals(nl.item(i).getAttributes().getNamedItem("status").getNodeValue()));
        nl = (NodeList) xpath.evaluate("/extension/share-files/file", responseXML, XPathConstants.NODESET);
        Map<String, Boolean> shareFiles = new HashMap<String, Boolean>(nl.getLength());
        for (int i = 0; i < nl.getLength(); i++)
            shareFiles.put(nl.item(i).getTextContent(),
                    "ok".equals(nl.item(i).getAttributes().getNamedItem("status").getNodeValue()));
        String motd = ((Node) xpath.evaluate("/extension/motd/text()", responseXML, XPathConstants.NODE))
                .getNodeValue();
        return new ExtensionUpdateInfo(extensionId, repoVersion, shareVersion, repoLatestVersion,
                shareLatestVersion, repoFiles, shareFiles, motd);
    } catch (Exception e) {
        return new ExtensionUpdateInfo(extensionId, repoVersion, shareVersion, "", "",
                new HashMap<String, Boolean>(), new HashMap<String, Boolean>(), "");
    }
}