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.google.android.apps.picview.request.CachedWebRequestFetcher.java

/** 
 * Fetches the given URL from the web.//w ww .j  ava  2s.  c  om
 */
public String fetchFromWeb(URL url) {

    Log.d(TAG, "Fetching from web: " + url.toString());
    HttpsURLConnection conn = null;
    HttpResponse resp = null;
    try {
        conn = (HttpsURLConnection) url.openConnection();
        conn.setUseCaches(false);
        conn.setReadTimeout(30000); // 30 seconds. 
        conn.setDoInput(true);
        conn.addRequestProperty("GData-Version", "2");
        conn.connect();
        InputStream is = conn.getInputStream();
        return readStringFromStream(is);
    } catch (Exception e) {
        Log.v(TAG, readStringFromStream(conn.getErrorStream()));
        e.printStackTrace();
    }
    return null;
}

From source file:com.apteligent.ApteligentJavaClient.java

/**
 * @param hash The crash hash to retrieve
 * @param diagnostics include detailed diagnostics information for crash
 * @param getOtherCrashes include other crashes and legacy crash groups now part of this group
 * @return Crash object//from   ww  w.j  ava 2 s  . c o  m
 */
public Crash getCrash(String hash, boolean diagnostics, boolean getOtherCrashes) {
    String params = "?diagnostics=" + diagnostics + "&get_other_crashes=" + getOtherCrashes;
    Crash crash = null;
    try {
        HttpsURLConnection conn = sendGetRequest(API_CRASH_DETAILS.replace("{hash}", hash), params);
        JsonFactory jsonFactory = new JsonFactory();
        JsonParser jp = jsonFactory.createParser(conn.getInputStream());
        ObjectMapper mapper = getObjectMapper();
        TreeNode node = mapper.readTree(jp);
        crash = mapper.treeToValue(node, Crash.class);
    } catch (IOException ioex) {
        ioex.printStackTrace();
    }
    return crash;
}

From source file:com.github.dfa.diaspora_android.task.GetPodsService.java

private void getPods() {
    /*//from ww  w  .  ja v a2s  .  c  o m
     * Most of the code in this AsyncTask is from the file getPodlistTask.java
     * from the app "Diaspora Webclient".
     * A few modifications and adaptations were made by me.
     * Source:
     * https://github.com/voidcode/Diaspora-Webclient/blob/master/src/com/voidcode/diasporawebclient/getPodlistTask.java
     * Thanks to Terkel Srensen ; License : GPLv3
     */
    AsyncTask<Void, Void, String[]> getPodsAsync = new AsyncTask<Void, Void, String[]>() {
        @Override
        protected String[] doInBackground(Void... params) {

            // TODO: Update deprecated code

            StringBuilder builder = new StringBuilder();
            //HttpClient client = new DefaultHttpClient();
            List<String> list = null;
            HttpsURLConnection connection;
            InputStream inStream;
            try {
                connection = NetCipher
                        .getHttpsURLConnection("https://podupti.me/api.php?key=4r45tg&format=json");
                int statusCode = connection.getResponseCode();
                if (statusCode == 200) {
                    inStream = connection.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inStream));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        builder.append(line);
                    }

                    try {
                        inStream.close();
                    } catch (IOException e) {
                        /*Nothing to do*/}

                    connection.disconnect();
                } else {
                    AppLog.e(this, "Failed to download list of pods");
                }
            } catch (IOException e) {
                //TODO handle json buggy feed
                e.printStackTrace();
            }
            //Parse the JSON Data
            try {
                JSONObject jsonObjectAll = new JSONObject(builder.toString());
                JSONArray jsonArrayAll = jsonObjectAll.getJSONArray("pods");
                AppLog.d(this, "Number of entries " + jsonArrayAll.length());
                list = new ArrayList<>();
                for (int i = 0; i < jsonArrayAll.length(); i++) {
                    JSONObject jo = jsonArrayAll.getJSONObject(i);
                    if (jo.getString("secure").equals("true"))
                        list.add(jo.getString("domain"));
                }

            } catch (Exception e) {
                //TODO Handle Parsing errors here
                e.printStackTrace();
            }
            if (list != null)
                return list.toArray(new String[list.size()]);
            else
                return null;
        }

        @Override
        protected void onPostExecute(String[] pods) {
            Intent broadcastIntent = new Intent(MESSAGE_PODS_RECEIVED);
            broadcastIntent.putExtra("pods", pods != null ? pods : new String[0]);
            LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(broadcastIntent);
            stopSelf();
        }
    };
    getPodsAsync.execute();
}

From source file:eu.hansolo.fx.weatherfx.darksky.DarkSky.java

public boolean update(final double LATITUDE, final double LONGITUDE) {
    // Update only if lastUpdate is older than 10 min
    if (Instant.now().minusSeconds(600).isBefore(lastUpdate))
        return true;

    StringBuilder response = new StringBuilder();
    try {//from ww w .j  a v a 2s . c om
        forecast.clear();
        alerts.clear();

        final String URL_STRING = createUrl(LATITUDE, LONGITUDE, unit, language, Exclude.HOURLY,
                Exclude.MINUTELY, Exclude.FLAGS);
        final HttpsURLConnection CONNECTION = (HttpsURLConnection) new URL(URL_STRING).openConnection();
        final BufferedReader IN = new BufferedReader(new InputStreamReader(CONNECTION.getInputStream()));
        String inputLine;
        while ((inputLine = IN.readLine()) != null) {
            response.append(inputLine).append("\n");
        }
        IN.close();

        Object obj = JSONValue.parse(response.toString());
        JSONObject jsonObj = (JSONObject) obj;

        latitude = Double.parseDouble(jsonObj.getOrDefault("latitude", 0).toString());
        longitude = Double.parseDouble(jsonObj.getOrDefault("longitude", 0).toString());
        timeZone = TimeZone.getTimeZone(jsonObj.getOrDefault("timezone", "").toString());

        // Update today data
        JSONObject currently = (JSONObject) jsonObj.get("currently");
        setDataPoint(today, currently);

        // Update forecast data
        JSONObject daily = (JSONObject) jsonObj.get("daily");
        JSONArray days = (JSONArray) daily.get("data");

        // Update today with more data
        JSONObject day0 = (JSONObject) days.get(0);
        today.setSunriseTime(epochStringToLocalDateTime(day0.getOrDefault("sunriseTime", 0).toString()));
        today.setSunsetTime(epochStringToLocalDateTime(day0.getOrDefault("sunsetTime", 0).toString()));
        today.setPrecipProbability(Double.parseDouble(day0.getOrDefault("precipProbability", 0).toString()));
        today.setPrecipType(PrecipType
                .valueOf(day0.getOrDefault("precipType", "none").toString().toUpperCase().replace("-", "_")));

        for (int i = 1; i < days.size(); i++) {
            JSONObject day = (JSONObject) days.get(i);
            DataPoint dataPoint = new DataPoint();
            setDataPoint(dataPoint, day);
            forecast.add(dataPoint);
        }

        // Update alert data
        if (jsonObj.containsKey("alerts")) {
            JSONArray alerts = (JSONArray) jsonObj.get("alerts");
            for (Object alertObj : alerts) {
                JSONObject alertJson = (JSONObject) alertObj;
                Alert alert = new Alert();
                alert.setTitle(alertJson.get("title").toString());
                alert.setDescription(alertJson.get("description").toString());
                alert.setTime(epochStringToLocalDateTime(alertJson.getOrDefault("time", 0).toString()));
                alert.setExpires(epochStringToLocalDateTime(alertJson.getOrDefault("expires", 0).toString()));
                alerts.add(alert);
            }
        }

        lastUpdate = Instant.now();

        return true;
    } catch (IOException ex) {
        System.out.println(ex);
        return false;
    }
}

From source file:com.webarch.common.net.http.HttpService.java

/**
 * ?Https//from w w w . ja  v  a2s  .com
 *
 * @param requestUrl    ?
 * @param requestMethod ?
 * @param trustManagers ??
 * @param outputJson    ?
 * @return 
 */
public static String doHttpsRequest(String requestUrl, String requestMethod, TrustManager[] trustManagers,
        String outputJson) {
    String result = null;
    try {
        StringBuffer buffer = new StringBuffer();
        // SSLContext??
        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
        sslContext.init(null, trustManagers, new java.security.SecureRandom());
        // SSLContextSSLSocketFactory
        SSLSocketFactory ssf = sslContext.getSocketFactory();
        URL url = new URL(requestUrl);
        HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
        httpUrlConn.setSSLSocketFactory(ssf);
        httpUrlConn.setDoOutput(true);
        httpUrlConn.setDoInput(true);
        httpUrlConn.setUseCaches(false);
        httpUrlConn.setUseCaches(false);
        httpUrlConn.setRequestProperty("Accept-Charset", DEFAULT_CHARSET);
        httpUrlConn.setRequestProperty("Content-Type", "application/json;charset=" + DEFAULT_CHARSET);
        // ?GET/POST
        httpUrlConn.setRequestMethod(requestMethod);

        if ("GET".equalsIgnoreCase(requestMethod))
            httpUrlConn.connect();

        // ????
        if (null != outputJson) {
            OutputStream outputStream = httpUrlConn.getOutputStream();
            //??
            outputStream.write(outputJson.getBytes(DEFAULT_CHARSET));
            outputStream.close();
        }

        // ???
        InputStream inputStream = httpUrlConn.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, DEFAULT_CHARSET);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String str = null;
        while ((str = bufferedReader.readLine()) != null) {
            buffer.append(str);
        }
        result = buffer.toString();
        bufferedReader.close();
        inputStreamReader.close();
        // ?
        inputStream.close();
        httpUrlConn.disconnect();
    } catch (ConnectException ce) {
        logger.error("Weixin server connection timed out.", ce);
    } catch (Exception e) {
        logger.error("https request error:", e);
    } finally {
        return result;
    }
}

From source file:org.croudtrip.activities.MainActivity.java

public void showUserInfoInNavigationDrawer() {

    // Get logged-in user and his data
    User user = AccountManager.getLoggedInUser(getApplicationContext());
    String firstName = (user == null || user.getFirstName() == null) ? "" : user.getFirstName();
    String lastName = (user == null || user.getLastName() == null) ? "" : user.getLastName();
    String email = (user == null || user.getEmail() == null) ? "" : user.getEmail();
    final String avatarUrl = (user == null || user.getAvatarUrl() == null) ? null : user.getAvatarUrl();
    Timber.i("Nav drawer avatarUrl is: " + avatarUrl);
    final MaterialAccount account = new MaterialAccount(this.getResources(), firstName + " " + lastName, email,
            R.drawable.profile, R.drawable.background_drawer);
    this.addAccount(account);
    // Download his avatar
    if (avatarUrl != null) {
        Observable.defer(new Func0<Observable<Bitmap>>() {
            @Override/*from  ww  w.  j av  a 2 s . com*/
            public Observable<Bitmap> call() {
                try {
                    URL url = new URL(avatarUrl);
                    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
                    connection.setDoInput(true);
                    connection.connect();
                    InputStream input = connection.getInputStream();
                    return Observable.just(BitmapFactory.decodeStream(input));
                } catch (Exception e) {
                    return Observable.error(e);
                }
            }
        }).compose(new DefaultTransformer<Bitmap>()).subscribe(new Action1<Bitmap>() {
            @Override
            public void call(Bitmap avatar) {
                Timber.d("avatar is null " + (avatar == null));
                Timber.d("" + avatar.getWidth());
                account.setPhoto(avatar);
                notifyAccountDataChanged();
            }
        }, new Action1<Throwable>() {
            @Override
            public void call(Throwable throwable) {
                Timber.e(throwable, "failed to download avatar");
            }
        });
    }
}

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

public void executeDownloadFileRequest(File filename) throws MarketoException {
    String err;// w  w  w  .  j av  a 2  s.c  o  m
    try {
        URL url = new URL(current_uri.toString());
        HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();
        urlConn.setRequestMethod("GET");
        urlConn.setRequestProperty("accept", "text/json");
        int responseCode = urlConn.getResponseCode();
        if (responseCode == 200) {
            InputStream inStream = urlConn.getInputStream();
            FileUtils.copyInputStreamToFile(inStream, filename);
        } else {
            err = String.format("Download failed for %s. Status: %d", filename, responseCode);
            throw new MarketoException(REST, err);
        }
    } catch (IOException e) {
        err = String.format("Download failed for %s. Cause: %s", filename, e.getMessage());
        LOG.error(err);
        throw new MarketoException(REST, err);
    }
}

From source file:org.openhab.binding.zonky.internal.ZonkyBinding.java

private String readResponse(HttpsURLConnection connection) throws Exception {
    InputStream stream = connection.getInputStream();
    String line;//  ww  w .  ja va  2 s  .  c  om
    StringBuilder body = new StringBuilder();
    BufferedReader reader = new BufferedReader(new InputStreamReader(stream));

    while ((line = reader.readLine()) != null) {
        body.append(line).append("\n");
    }
    line = body.toString();
    logger.debug("Response: {}", line);
    return line;
}

From source file:snow.http.auth.Facebook.java

private Term fetchProfile(String accessToken) {
    try {//  w w w.ja v a  2s .c  om

        URL url = new URL(PROFILE + accessToken);// +"&appsecret_proof="+MDigest.HmacSHA256(AppSecret,
                                                 // accessToken));

        // System.out.println(url);

        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();

        try (InputStream stream = con.getInputStream()) {

            if (con.getResponseCode() == 200) {

                ObjectMapper mapper = new ObjectMapper();

                JsonNode root = mapper.readTree(url.openStream());

                JsonNode node = root.get("id");
                if (node != null) {
                    String fbID = node.asText();

                    //                        try (Transaction tx = Core.DB.beginTx()) {
                    //                            TermMutable term;
                    //                            Node termNode = Core.search(FACEBOOK_ID, fbID);
                    //                            if (termNode == null) {
                    //                                term = Unstable.term();
                    //
                    //                                term.property(FACEBOOK_ID, fbID);
                    //
                    //                                term.type(Primitives.PERSON);
                    //                            } else {
                    //                                term = TermInDB.term(termNode);
                    //                            }
                    //
                    //                            term.link(new URL("https://www.facebook.com/profile.php?id=" + fbID));
                    //
                    //                            for (String field : FIELDS) {
                    //                                node = root.get(field);
                    //
                    //                                if (node != null) {
                    //                                    switch (field) {
                    //                                    case "languages":
                    //                                        // XXX: code
                    //                                        break;
                    //
                    //                                    case "picture":
                    //                                        JsonNode data = node.get("data");
                    //                                        if (data != null) {
                    //                                            JsonNode picURL = data.get("url");
                    //                                            if (picURL != null) {
                    //                                                try {
                    //                                                    URL imgURL = new URL(picURL.asText());
                    //
                    //                                                    term.property("facebook:" + field, imgURL.toString());
                    //
                    //                                                    term.visual(imgURL);
                    //                                                } catch (MalformedURLException e) {
                    //                                                }
                    //                                            }
                    //                                        }
                    //
                    //                                        break;
                    //
                    //                                    case "name":
                    //                                        term.label(ORIGINAL_LANGUAGE, node.asText());
                    //
                    //                                    default:
                    //                                        term.property("facebook:" + field, node.asText());
                    //
                    //                                        break;
                    //                                    }
                    //                                }
                    //                            }
                    //
                    //                            // System.out.println("term = "+term.debug(0));
                    //
                    //                            TermInDB person = TermInDB.term(term);
                    //
                    //                            tx.success();
                    //
                    //                            return person;
                    //                        }
                }
            }
        } catch (IOException e) {
            // e.printStackTrace();
            //
            // System.out.println("response code = "+con.getResponseCode());
            //
            // try (InputStream stream = con.getErrorStream()) {
            // java.util.Scanner s = new
            // java.util.Scanner(stream).useDelimiter("\\A");
            // System.out.println(s.hasNext() ? s.next() : "");
            // }
        }

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:snow.http.auth.Facebook.java

@Override
public boolean handle(ChannelHandlerContext ctx, FullHttpRequest request) throws Throwable {
    String uri = request.getUri();
    if (!uri.startsWith(ROOT))
        return false;

    if (!request.getMethod().equals(GET)) {
        HttpErrorHelper.handle(ctx, request, METHOD_NOT_ALLOWED);
        return true;
    }//w  w w . j  av  a  2s.co m

    // System.out.println(uri);

    String function = uri.substring(ROOT.length());

    if (function.startsWith("facebook/")) {

        Session session = SessionRegistry._.active();

        if (session != null) {
            Long expiresAt = session.getLong(EXPIRES_AT);
            if (expiresAt != null) {
                if (expiresAt > System.currentTimeMillis()) {
                    sendRedirect(ctx, request, "/");
                    return true;
                } else {
                    session.remove(ACCESS_TOKEN);
                    session.remove(EXPIRES_AT);
                    session.remove(SUBJECT);
                }
            }
        }

        FastMap<String, String> map = new FastMap<String, String>();
        try {

            parseParams(map, function);

            if (map.containsKey("error")) {
                HttpErrorHelper.handle(ctx, request, FORBIDDEN);
                return true;

            } else if (map.containsKey("error_code")) {
                HttpErrorHelper.handle(ctx, request, FORBIDDEN);
                return true;

            } else if (map.containsKey("code")) {

                if (map.containsKey(STATE)) {
                    if (session != null && !map.get(STATE).equals(session.ID()._)) {
                        HttpErrorHelper.handle(ctx, request, UNAUTHORIZED);
                        return true;
                    } else {
                        session = SessionRegistry._.activate(map.get(STATE));

                        // check 'state'
                        if (session == null || !map.get(STATE).equals(session.ID()._)) {
                            HttpErrorHelper.handle(ctx, request, UNAUTHORIZED);
                            return true;
                        }
                    }
                } else {
                    HttpErrorHelper.handle(ctx, request, UNAUTHORIZED);
                    return true;
                }

                URL url = new URL(AUTH + map.get("code").trim());

                HttpsURLConnection con = (HttpsURLConnection) url.openConnection();

                try (InputStream stream = con.getInputStream()) {

                    if (con.getResponseCode() == 200) {

                        readAccessToken(stream);
                    }

                } catch (IOException e) {
                    HttpErrorHelper.handle(ctx, request, FORBIDDEN);
                    return true;
                }

                sendRedirect(ctx, request, "/");
                return true;
            }

            if (session == null)
                session = SessionRegistry._.make();

            sendRedirect(ctx, request, AUTHORIZE + session.ID()._);
            return true;

        } catch (Throwable e) {
            e.printStackTrace();
            HttpErrorHelper.handle(ctx, request, INTERNAL_SERVER_ERROR);
            return true;
        }

    } else {
        HttpErrorHelper.handle(ctx, request, NOT_FOUND);
        return true;
    }
}