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:com.tohours.imo.util.TohoursUtils.java

/**
 * //from  ww  w. jav a 2  s. c  om
 * @param path
 * @param charsetName
 * @return
 * @throws IOException
 */
public static String httpsGet(String path, String charsetName) throws IOException {
    String rv = null;
    URL url = null;
    HttpsURLConnection httpsConnection = null;
    InputStream input = null;
    try {
        url = new URL(path);
        httpsConnection = (HttpsURLConnection) url.openConnection();
        input = httpsConnection.getInputStream();
        rv = TohoursUtils.inputStream2String(input, charsetName);
    } finally {
        if (input != null) {
            input.close();
        }
    }
    return rv;
}

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/*from   w w w.  j  av a  2s.  c o  m*/
 * @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:com.rmtheis.yandtran.YandexTranslatorAPI.java

/**
 * Forms an HTTPS request, sends it using GET method and returns the result of the request as a String.
 * //from  w  ww . j  a  v  a 2s  .  c  o  m
 * @param url The URL to query for a String response.
 * @return The translated String.
 * @throws Exception on error.
 */
private static String retrieveResponse(final URL url) throws Exception {
    final HttpsURLConnection uc = (HttpsURLConnection) url.openConnection();
    if (referrer != null)
        uc.setRequestProperty("referer", referrer);
    uc.setRequestProperty("Content-Type", "text/plain; charset=" + ENCODING);
    uc.setRequestProperty("Accept-Charset", ENCODING);
    uc.setRequestMethod("GET");

    try {
        final int responseCode = uc.getResponseCode();
        final String result = inputStreamToString(uc.getInputStream());
        if (responseCode != 200) {
            throw new Exception("Error from Yandex API: " + result);
        }
        return result;
    } finally {
        if (uc != null) {
            uc.disconnect();
        }
    }
}

From source file:org.eclipse.agail.recommenderserver.Recommenders.java

private static ListOfWFs updateFlowsNodes(ListOfWFs wflist) {

    for (int i = 0; i < wflist.getWfList().size(); i++) {

        // UPDATE LINK
        wflist.getWfList().get(i).setHref("https://flows.nodered.org" + wflist.getWfList().get(i).getHref());

        char[] out = new char[12000];
        URL url;/*w  w  w .j  av  a  2  s .  c  o  m*/
        try {

            url = new URL(wflist.getWfList().get(i).getHref().toString());
            HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
            con.setRequestProperty("User-Agent",
                    "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
            con.connect();
            InputStream input = con.getInputStream();
            byte[] bytes = IOUtils.toByteArray(input);

            String str = new String(bytes);
            String substr = str;
            // ADD DESCRIPTION
            // flow-description"> or "flow-title">
            int start = str.lastIndexOf("flow-description\">");
            if (start != -1) {
                substr = str.substring(start);
                start = substr.indexOf(">");
                start += 1;
                substr = substr.substring(start);
            }

            else {
                start = str.lastIndexOf("flow-title\">");
                start += 12;
                substr = str.substring(start);
                start = substr.indexOf("<p>");
                start += 3;
                substr = substr.substring(start);
            }

            int end = substr.indexOf("</p>");
            String desc = substr.substring(0, end);
            wflist.getWfList().get(i).setDescription(desc);

            // ADD JS CODE
            if (wflist.getWfList().get(i).getType().equals("flow")) {

                start = str.indexOf("javascript\">");
                start += 12;
                substr = str.substring(start);
                end = substr.indexOf("</pre>");

                StringEscapeUtils util = new StringEscapeUtils();

                String code = substr.substring(0, end);
                code = util.unescapeHtml4(code);
                //               code = code.replace("&quot;", "\"");
                //               code = code.replace("&lt;", "<");
                //               code = code.replace("&gt;", ">");
                //               code = code.replace("&#x3D;", "=");
                //               code = code.replace("&#39;", "'");
                //               code = code.replace("&#x2F;", "/");
                wflist.getWfList().get(i).setJavascriptCode(code);
            }

            // ADD INSTALL COMMAND
            if (wflist.getWfList().get(i).getType().equals("node")) {
                start = str.indexOf("<code>npm install ");
                start += 6;
                substr = str.substring(start);
                end = substr.indexOf("</code>");

                String command = substr.substring(0, end);
                wflist.getWfList().get(i).setInstallCommand(command);
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    return wflist;
}

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");
    }/*from  w  w  w .  ja v  a 2 s.c  o  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.CellsFactory.java

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

    if (conn.getResponseCode() / 100 >= 3) {
        String s = new String(IOUtils.toByteArray(conn.getErrorStream()));
        throw new RuntimeException(s);
    }/*  w ww . java 2 s .c  o m*/

    XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
    factory.setNamespaceAware(true);
    XmlPullParser xpp = factory.newPullParser();
    xpp.setInput(new BufferedReader(new InputStreamReader(conn.getInputStream())));

    int eventType = xpp.getEventType();

    List<Row> rowList = new ArrayList<Row>(100);
    Row row = null;
    String lastTag = "";
    int currentRow = 1;
    int currentCol = 1;
    Cells cells = new Cells();
    while (eventType != XmlPullParser.END_DOCUMENT) {

        if (eventType == XmlPullParser.START_DOCUMENT) {
        } else if (eventType == XmlPullParser.START_TAG) {
            lastTag = xpp.getName();
            if (xpp.getName().equals("cell")) {
                currentRow = Integer.valueOf(xpp.getAttributeValue(null, "row"));
                currentCol = Integer.valueOf(xpp.getAttributeValue(null, "col"));
            }
        } else if (eventType == XmlPullParser.END_TAG) {
            if (xpp.getName().equals("entry")) {
                rowList.add(row);
                row = null;
            }
        } else if (eventType == XmlPullParser.TEXT) {
            if (lastTag.equals("cell")) {
                cells.addCell(currentRow, currentCol, xpp.getText());
            }
            if (lastTag.equals("title") && Strings.isNullOrEmpty(cells.getWorksheetName())) {
                cells.setWorksheetName(xpp.getText());
            }
        }
        eventType = xpp.next();
    }
    return cells;
}

From source file:give_me_coins.dashboard.JSONHelper.java

private static JSONObject getJSONFromUrl(URL para_url) {
    //   ProgressDialog oShowProgress = ProgressDialog.show(oAct, "Loading", "Loading", true, false);
    JSONObject oRetJson = null;/*from  w w w  .  ja  v a2 s.  co  m*/

    try {

        //Log.d(TAG,para_url.toString());
        BufferedInputStream oInput = null;

        HttpsURLConnection oConnection = (HttpsURLConnection) para_url.openConnection();
        //   HttpsURLConnection.setDefaultHostnameVerifier(org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        oConnection.setConnectTimeout(iConnectionTimeout);
        oConnection.setReadTimeout(iConnectionTimeout * 2);
        //      connection.setRequestProperty ("Authorization", sAuthorization);
        oConnection.connect();
        oInput = new BufferedInputStream(oConnection.getInputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(oInput));
        String sReturn = reader.readLine();
        //Log.d(TAG,sReturn);

        oRetJson = new JSONObject(sReturn);

    } catch (SocketTimeoutException e) {
        Log.d(TAG, "Timeout");
    } catch (IOException e) {
        Log.e(TAG, e.toString());

    } catch (JSONException e) {
        Log.e(TAG, e.toString());
    }

    catch (Exception e) {
        Log.e(TAG, e.toString());
    }

    //para_ProgressDialog.dismiss();
    return oRetJson;

}

From source file:com.dmsl.anyplace.utils.NetworkUtils.java

public static InputStream downloadHttps(String urlS) throws IOException, URISyntaxException {
    InputStream is = null;/*from w  w w  .  ja v  a  2s  .  c om*/

    URL url = new URL(encodeURL(urlS));

    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setReadTimeout(10000);
    conn.setConnectTimeout(15000);
    conn.setRequestMethod("GET");
    conn.setDoInput(true);

    conn.connect();

    int response = conn.getResponseCode();
    if (response == 200) {
        is = conn.getInputStream();
    }

    return is;
}

From source file:com.aware.ui.Plugins_Manager.java

/**
* Downloads and compresses image for optimized icon caching
* @param image_url/*from   w  ww  .  j  a va 2 s. com*/
* @return
*/
public static byte[] cacheImage(String image_url, Context sContext) {
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        InputStream caInput = sContext.getResources().openRawResource(R.raw.aware);
        Certificate ca;
        try {
            ca = cf.generateCertificate(caInput);
        } finally {
            caInput.close();
        }

        KeyStore sKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        InputStream inStream = sContext.getResources().openRawResource(R.raw.awareframework);
        sKeyStore.load(inStream, "awareframework".toCharArray());
        inStream.close();

        sKeyStore.setCertificateEntry("ca", ca);

        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(sKeyStore);

        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, tmf.getTrustManagers(), null);

        //Fetch image now that we recognise SSL
        URL image_path = new URL(image_url.replace("http://", "https://")); //make sure we are fetching the images over https
        HttpsURLConnection image_connection = (HttpsURLConnection) image_path.openConnection();
        image_connection.setSSLSocketFactory(context.getSocketFactory());

        InputStream in_stream = image_connection.getInputStream();
        Bitmap tmpBitmap = BitmapFactory.decodeStream(in_stream);
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        tmpBitmap.compress(Bitmap.CompressFormat.PNG, 100, output);

        return output.toByteArray();

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:au.id.micolous.frogjump.Util.java

public static void updateCheck(final Activity activity) {
    (new AsyncTask<Void, Void, Boolean>() {
        @Override//from   ww  w.j a  v a 2 s.c  o m
        protected Boolean doInBackground(Void... voids) {
            try {
                String my_version = Integer.toString(getVersionCode());
                URL url = new URL("https://micolous.github.io/frogjump/version.json");
                HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setDoInput(true);
                conn.setReadTimeout(10000);
                conn.setConnectTimeout(15000);
                conn.connect();

                int responseCode = conn.getResponseCode();
                if (responseCode == 200) {
                    InputStream is = conn.getInputStream();
                    byte[] buffer = new byte[1024];
                    if (is.read(buffer) == 0) {
                        Log.i(TAG, "Error reading update file, 0 bytes");
                        return false;
                    }
                    JSONObject root = (JSONObject) new JSONTokener(new String(buffer, "US-ASCII")).nextValue();

                    if (root.has(my_version)) {
                        if (root.getBoolean(my_version)) {
                            // Definitely needs update.
                            Log.i(TAG, "New version required, explicit flag.");
                            return true;
                        }
                    } else {
                        // unlisted version, assume it is old.
                        Log.i(TAG, "New version required, not in list.");
                        return true;
                    }

                }
            } catch (Exception ex) {
                Log.e(TAG, "Error getting update info", ex);
            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean needsUpdate) {
            if (needsUpdate)
                newVersionAlert(activity);
        }
    }).execute();
}