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:org.schabi.newpipe.Downloader.java

/** AsyncTask impl: executed in background thread does the download */
@Override/* w  w  w.j a va  2s.  co  m*/
protected Void doInBackground(Void... voids) {
    HttpsURLConnection con = null;
    InputStream inputStream = null;
    FileOutputStream outputStream = null;
    try {
        con = NetCipher.getHttpsURLConnection(fileURL);
        int responseCode = con.getResponseCode();

        // always check HTTP response code first
        if (responseCode == HttpURLConnection.HTTP_OK) {
            fileSize = con.getContentLength();
            inputStream = new BufferedInputStream(con.getInputStream());
            outputStream = new FileOutputStream(saveFilePath);

            int bufferSize = 8192;
            int downloaded = 0;

            int bytesRead = -1;
            byte[] buffer = new byte[bufferSize];
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
                downloaded += bytesRead;
                if (downloaded % 50000 < bufferSize) {
                    publishProgress(downloaded);
                }
            }

            publishProgress(bufferSize);

        } else {
            Log.i(TAG, "No file to download. Server replied HTTP code: " + responseCode);
        }
    } catch (IOException e) {
        Log.e(TAG, "No file to download. Server replied HTTP code: ", e);
        e.printStackTrace();
    } finally {
        try {
            if (outputStream != null) {
                outputStream.close();
                outputStream = null;
            }
            if (inputStream != null) {
                inputStream.close();
                inputStream = null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (con != null) {
            con.disconnect();
            con = null;
        }
    }
    return null;
}

From source file:org.wso2.carbon.automation.test.utils.http.client.HttpsURLConnectionClient.java

public static HttpsResponse postWithBasicAuth(String uri, String requestQuery, String userName, String password)
        throws IOException {
    if (uri.startsWith("https://")) {
        URL url = new URL(uri);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        String encode = new String(
                new org.apache.commons.codec.binary.Base64().encode((userName + ":" + password).getBytes()))
                        .replaceAll("\n", "");
        ;/*from ww w  . ja  v  a2  s  .  c om*/
        conn.setRequestProperty("Authorization", "Basic " + encode);
        conn.setDoOutput(true); // Triggers POST.
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("charset", "utf-8");
        conn.setRequestProperty("Content-Length", "" + Integer.toString(requestQuery.getBytes().length));
        conn.setUseCaches(false);
        conn.setHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(requestQuery);
        conn.setReadTimeout(10000);
        conn.connect();
        System.out.println(conn.getRequestMethod());
        // Get the response
        StringBuilder sb = new StringBuilder();
        BufferedReader rd = null;
        try {
            rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), Charset.defaultCharset()));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
            return new HttpsResponse(sb.toString(), conn.getResponseCode());
        } catch (FileNotFoundException ignored) {
        } finally {
            if (rd != null) {
                rd.close();
            }
            wr.flush();
            wr.close();
            conn.disconnect();
        }
    }
    return null;
}

From source file:com.illusionaryone.GameWispAPI.java

@SuppressWarnings("UseSpecificCatch")
private static JSONObject readJsonFromUrl(String methodType, String urlAddress) {
    JSONObject jsonResult = new JSONObject("{}");
    InputStream inputStream = null;
    OutputStream outputStream = null;
    URL urlRaw;/*from  www .j  a  v a 2 s .  c o  m*/
    HttpsURLConnection urlConn;
    String jsonText = "";

    if (sAccessToken.length() == 0) {
        if (!noAccessWarning) {
            com.gmt2001.Console.err.println(
                    "GameWispAPI: Attempting to use GameWisp API without key. Disable GameWisp module.");
            noAccessWarning = true;
        }
        JSONStringer jsonObject = new JSONStringer();
        return (new JSONObject(jsonObject.object().key("result").object().key("status").value(-1).endObject()
                .endObject().toString()));
    }

    try {
        urlRaw = new URL(urlAddress);
        urlConn = (HttpsURLConnection) urlRaw.openConnection();
        urlConn.setDoInput(true);
        urlConn.setRequestMethod(methodType);
        urlConn.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");

        if (methodType.equals("POST")) {
            urlConn.setDoOutput(true);
            urlConn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        } else {
            urlConn.addRequestProperty("Content-Type", "application/json");
        }

        urlConn.connect();

        if (urlConn.getResponseCode() == 200) {
            inputStream = urlConn.getInputStream();
        } else {
            inputStream = urlConn.getErrorStream();
        }

        BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
        jsonText = readAll(rd);
        jsonResult = new JSONObject(jsonText);
        fillJSONObject(jsonResult, true, methodType, urlAddress, urlConn.getResponseCode(), "", "", jsonText);
    } catch (JSONException ex) {
        fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "JSONException", ex.getMessage(),
                jsonText);
        com.gmt2001.Console.err
                .println("GameWispAPI::Bad JSON (" + urlAddress + "): " + jsonText.substring(0, 100) + "...");
    } catch (NullPointerException ex) {
        fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "NullPointerException", ex.getMessage(),
                "");
        com.gmt2001.Console.err.println("GameWispAPI::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (MalformedURLException ex) {
        fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "MalformedURLException", ex.getMessage(),
                "");
        com.gmt2001.Console.err.println("GameWispAPI::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (SocketTimeoutException ex) {
        fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "SocketTimeoutException", ex.getMessage(),
                "");
        com.gmt2001.Console.err.println("GameWispAPI::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (IOException ex) {
        fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "IOException", ex.getMessage(), "");
        com.gmt2001.Console.err.println("GameWispAPI::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (Exception ex) {
        fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "Exception", ex.getMessage(), "");
        com.gmt2001.Console.err.println("GameWispAPI::readJsonFromUrl::Exception: " + ex.getMessage());
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException ex) {
                fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "IOException", ex.getMessage(),
                        "");
                com.gmt2001.Console.err.println("GameWispAPI::readJsonFromUrl::Exception: " + ex.getMessage());
            }
        }
    }

    return (jsonResult);
}

From source file:org.openhab.binding.neato.internal.VendorVorwerk.java

@Override
public String executeRequest(String httpMethod, String url, Properties httpHeaders, InputStream content,
        String contentType, int timeout) throws IOException {

    URL requestUrl = new URL(url);
    HttpsURLConnection connection = (HttpsURLConnection) requestUrl.openConnection();
    applyNucleoSslConfiguration(connection);
    connection.setRequestMethod(httpMethod);
    for (String propName : httpHeaders.stringPropertyNames()) {
        connection.addRequestProperty(propName, httpHeaders.getProperty(propName));
    }//from  w w w. j  av a2 s .co m
    connection.setUseCaches(false);
    connection.setDoOutput(true);
    connection.setConnectTimeout(10000);
    connection.setReadTimeout(10000);
    content.reset();
    IOUtils.copy(content, connection.getOutputStream());

    java.io.InputStream is = connection.getInputStream();
    return IOUtils.toString(is);
}

From source file:org.openintents.lib.DeliciousApiHelper.java

public String[] getTags() throws java.io.IOException {

    String[] result = null;/*ww  w.j a  v  a2 s  .co  m*/
    String rpc = mAPI + "tags/get";
    Element tag;
    java.net.URL u = null;

    try {
        u = new URL(rpc);

    } catch (java.net.MalformedURLException mu) {
        System.out.println("Malformed URL>>" + mu.getMessage());
    }

    Document doc = null;

    try {
        javax.net.ssl.HttpsURLConnection connection = (javax.net.ssl.HttpsURLConnection) u.openConnection();
        //that's actualy pretty ugly to do, but a neede workaround for m5.rc15
        javax.net.ssl.HostnameVerifier v = new org.apache.http.conn.ssl.AllowAllHostnameVerifier();

        connection.setHostnameVerifier(v);

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();

        doc = db.parse(connection.getInputStream());

    } catch (java.io.IOException ioe) {
        System.out.println("Error >>" + ioe.getMessage());
        Log.e(_TAG, "Error >>" + ioe.getMessage());

    } catch (ParserConfigurationException pce) {
        System.out.println("ERror >>" + pce.getMessage());
        Log.e(_TAG, "ERror >>" + pce.getMessage());
    } catch (SAXException se) {
        System.out.println("ERRROR>>" + se.getMessage());
        Log.e(_TAG, "ERRROR>>" + se.getMessage());

    } catch (Exception e) {
        Log.e(_TAG, "Error while excecuting HTTP method. URL is: " + u);
        System.out.println("Error while excecuting HTTP method. URL is: " + u);
        e.printStackTrace();
    }

    if (doc == null) {
        Log.e(_TAG, "document was null, check internet connection?");
        throw new java.io.IOException("Error reading stream >>" + rpc + "<<");

    }
    int tagsLen = doc.getElementsByTagName("tag").getLength();
    result = new String[tagsLen];
    for (int i = 0; i < tagsLen; i++) {
        tag = (Element) doc.getElementsByTagName("tag").item(i);
        result[i] = new String(tag.getAttribute("tag").trim());
    }

    //System.out.println( new Scanner( u.openStream() ).useDelimiter( "\\Z" ).next() );
    return result;
}

From source file:org.apache.hadoop.http.TestSSLHttpServer.java

/**
 * Test that verifies that excluded ciphers (SSL_RSA_WITH_RC4_128_SHA,
 * TLS_ECDH_ECDSA_WITH_RC4_128_SHA,TLS_ECDH_RSA_WITH_RC4_128_SHA,
 * TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,TLS_ECDHE_RSA_WITH_RC4_128_SHA) are not
 * available for negotiation during SSL connection.
 */// www.  j  ava  2  s.c o  m
@Test
public void testExcludedCiphers() throws Exception {
    URL url = new URL(baseUrl, "/echo?a=b&c=d");
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    SSLSocketFactory sslSocketF = clientSslFactory.createSSLSocketFactory();
    PrefferedCipherSSLSocketFactory testPreferredCipherSSLSocketF = new PrefferedCipherSSLSocketFactory(
            sslSocketF, excludeCiphers.split(","));
    conn.setSSLSocketFactory(testPreferredCipherSSLSocketF);
    assertFalse("excludedCipher list is empty", excludeCiphers.isEmpty());
    try {
        InputStream in = conn.getInputStream();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        IOUtils.copyBytes(in, out, 1024);
        fail("No Ciphers in common, SSLHandshake must fail.");
    } catch (SSLHandshakeException ex) {
        LOG.info("No Ciphers in common, expected succesful test result.", ex);
    }
}

From source file:org.apache.hadoop.http.TestSSLHttpServer.java

/** Test that verified that additionally included cipher
 * TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA is only available cipher for working
 * TLS connection from client to server disabled for all other common ciphers.
 *///  ww w.  j  a va2 s .  c o  m
@Test
public void testOneEnabledCiphers() throws Exception {
    URL url = new URL(baseUrl, "/echo?a=b&c=d");
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    SSLSocketFactory sslSocketF = clientSslFactory.createSSLSocketFactory();
    PrefferedCipherSSLSocketFactory testPreferredCipherSSLSocketF = new PrefferedCipherSSLSocketFactory(
            sslSocketF, oneEnabledCiphers.split(","));
    conn.setSSLSocketFactory(testPreferredCipherSSLSocketF);
    assertFalse("excludedCipher list is empty", oneEnabledCiphers.isEmpty());
    try {
        InputStream in = conn.getInputStream();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        IOUtils.copyBytes(in, out, 1024);
        assertEquals(out.toString(), "a:b\nc:d\n");
        LOG.info("Atleast one additional enabled cipher than excluded ciphers,"
                + " expected successful test result.");
    } catch (SSLHandshakeException ex) {
        fail("Atleast one additional cipher available for successful handshake." + " Unexpected test failure: "
                + ex);
    }
}

From source file:org.apache.hadoop.http.TestSSLHttpServer.java

/** Test verifies that mutually exclusive server's disabled cipher suites and
 * client's enabled cipher suites can successfully establish TLS connection.
 *//*from  w  ww  .  ja v  a 2  s  . c o m*/
@Test
public void testExclusiveEnabledCiphers() throws Exception {
    URL url = new URL(baseUrl, "/echo?a=b&c=d");
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    SSLSocketFactory sslSocketF = clientSslFactory.createSSLSocketFactory();
    PrefferedCipherSSLSocketFactory testPreferredCipherSSLSocketF = new PrefferedCipherSSLSocketFactory(
            sslSocketF, exclusiveEnabledCiphers.split(","));
    conn.setSSLSocketFactory(testPreferredCipherSSLSocketF);
    assertFalse("excludedCipher list is empty", exclusiveEnabledCiphers.isEmpty());
    try {
        InputStream in = conn.getInputStream();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        IOUtils.copyBytes(in, out, 1024);
        assertEquals(out.toString(), "a:b\nc:d\n");
        LOG.info("Atleast one additional enabled cipher than excluded ciphers,"
                + " expected successful test result.");
    } catch (SSLHandshakeException ex) {
        fail("Atleast one additional cipher available for successful handshake." + " Unexpected test failure: "
                + ex);
    }
}

From source file:com.mikhaellopez.saveinsta.activity.MainActivity.java

private boolean downloadVideo(String urlVideo, String fileName) {
    boolean result = false;
    OutputStream output = null;//from   www.  ja  va  2s  . co  m
    InputStream input = null;
    try {
        File root = new File(Environment.getExternalStorageDirectory() + File.separator
                + getResources().getString(R.string.app_name) + File.separator);
        root.mkdirs();
        File sdImageMainDirectory = new File(root, fileName);

        // Download Video
        URL url = new URL(urlVideo);
        HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
        urlConnection.connect();

        input = urlConnection.getInputStream();
        output = new FileOutputStream(sdImageMainDirectory);

        byte[] data = new byte[input.available()];
        input.read(data);
        output.write(data);

        byte[] buffer = new byte[1024];
        int len1;
        while ((len1 = input.read(buffer)) > 0) {
            output.write(buffer, 0, len1);
        }

        result = true;
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (null != output) {
            try {
                output.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (null != input) {
            try {
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return result;
}

From source file:Activities.java

private String addData(String endpoint) {
    String data = null;//  ww w.  j a v a 2s . c  o m
    try {
        // Construct request payload
        JSONObject attrObj = new JSONObject();
        attrObj.put("name", "URL");
        attrObj.put("value", "http://www.nvidia.com/game-giveaway");

        JSONArray attrArray = new JSONArray();
        attrArray.add(attrObj);

        TimeZone tz = TimeZone.getTimeZone("UTC");
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
        df.setTimeZone(tz);
        String dateAsISO = df.format(new Date());

        // Required attributes
        JSONObject obj = new JSONObject();
        obj.put("leadId", "1001");
        obj.put("activityDate", dateAsISO);
        obj.put("activityTypeId", "1001");
        obj.put("primaryAttributeValue", "Game Giveaway");
        obj.put("attributes", attrArray);
        System.out.println(obj);

        // Make request
        URL url = new URL(endpoint);
        HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();
        urlConn.setRequestMethod("POST");
        urlConn.setAllowUserInteraction(false);
        urlConn.setDoOutput(true);
        urlConn.setRequestProperty("Content-type", "application/json");
        urlConn.setRequestProperty("accept", "application/json");
        urlConn.connect();
        OutputStream os = urlConn.getOutputStream();
        os.write(obj.toJSONString().getBytes());
        os.close();

        // Inspect response
        int responseCode = urlConn.getResponseCode();
        if (responseCode == 200) {
            System.out.println("Status: 200");
            InputStream inStream = urlConn.getInputStream();
            data = convertStreamToString(inStream);
            System.out.println(data);
        } else {
            System.out.println(responseCode);
            data = "Status:" + responseCode;
        }
    } catch (MalformedURLException e) {
        System.out.println("URL not valid.");
    } catch (IOException e) {
        System.out.println("IOException: " + e.getMessage());
        e.printStackTrace();
    }

    return data;
}