Example usage for com.squareup.okhttp OkHttpClient newCall

List of usage examples for com.squareup.okhttp OkHttpClient newCall

Introduction

In this page you can find the example usage for com.squareup.okhttp OkHttpClient newCall.

Prototype

public Call newCall(Request request) 

Source Link

Document

Prepares the request to be executed at some point in the future.

Usage

From source file:at.aau.itec.android.mediaplayer.dash.DashParser.java

License:Open Source License

/**
 * Parses an MPD XML file. This needs to be executed off the main thread, else a
 * NetworkOnMainThreadException gets thrown.
 * @param source the URl of an MPD XML file
 * @return a MPD object//from   w  w w.  j  a  v a2  s  .  c om
 * @throws android.os.NetworkOnMainThreadException if executed on the main thread
 */
public MPD parse(UriSource source) {
    MPD mpd = null;
    OkHttpClient httpClient = new OkHttpClient();

    Headers.Builder headers = new Headers.Builder();
    if (source.getHeaders() != null && !source.getHeaders().isEmpty()) {
        for (String name : source.getHeaders().keySet()) {
            headers.add(name, source.getHeaders().get(name));
        }
    }

    Request.Builder request = new Request.Builder().url(source.getUri().toString()).headers(headers.build());

    try {
        Response response = httpClient.newCall(request.build()).execute();
        if (!response.isSuccessful()) {
            throw new IOException("error requesting the MPD");
        }
        mpd = parse(response.body().byteStream());
    } catch (IOException e) {
        Log.e(TAG, "error downloading the MPD", e);
        throw new RuntimeException("error downloading the MPD", e);
    } catch (XmlPullParserException e) {
        Log.e(TAG, "error parsing the MPD", e);
        throw new RuntimeException("error parsing the MPD", e);
    }

    return mpd;
}

From source file:butter.droid.base.providers.subs.SubsProvider.java

License:Open Source License

/**
 * @param context      Context/*from ww  w  .ja v a 2s . c  om*/
 * @param media        Media data
 * @param languageCode Code of language
 * @param callback     Network callback
 * @return Call
 */
public static Call download(final Context context, final Media media, final String languageCode,
        final com.squareup.okhttp.Callback callback) {
    OkHttpClient client = ButterApplication.getHttpClient();
    if (media.subtitles != null && media.subtitles.containsKey(languageCode)) {
        try {
            Request request = new Request.Builder().url(media.subtitles.get(languageCode)).build();
            Call call = client.newCall(request);

            final File subsDirectory = getStorageLocation(context);
            final String fileName = media.videoId + "-" + languageCode;
            final File srtPath = new File(subsDirectory, fileName + ".srt");

            if (srtPath.exists()) {
                callback.onResponse(null);
                return call;
            }

            call.enqueue(new com.squareup.okhttp.Callback() {
                @Override
                public void onFailure(Request request, IOException e) {
                    callback.onFailure(request, e);
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    if (response.isSuccessful()) {
                        InputStream inputStream = null;
                        boolean failure = false;
                        try {

                            subsDirectory.mkdirs();
                            if (srtPath.exists()) {
                                File to = new File(subsDirectory, "temp" + System.currentTimeMillis());
                                srtPath.renameTo(to);
                                to.delete();
                            }

                            inputStream = response.body().byteStream();
                            String urlString = response.request().urlString();

                            if (urlString.contains(".zip") || urlString.contains(".gz")) {
                                SubsProvider.unpack(inputStream, srtPath, languageCode);
                            } else if (SubsProvider.isSubFormat(urlString)) {
                                parseFormatAndSave(urlString, srtPath, languageCode, inputStream);
                            } else {
                                callback.onFailure(response.request(),
                                        new IOException("FatalParsingException"));
                                failure = true;
                            }
                        } catch (FatalParsingException e) {
                            e.printStackTrace();
                            callback.onFailure(response.request(), new IOException("FatalParsingException"));
                            failure = true;
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                            callback.onFailure(response.request(), e);
                            failure = true;
                        } catch (IOException e) {
                            e.printStackTrace();
                            callback.onFailure(response.request(), e);
                            failure = true;
                        } finally {
                            if (inputStream != null)
                                inputStream.close();

                            if (!failure)
                                callback.onResponse(response);
                        }
                    } else {
                        callback.onFailure(response.request(), new IOException("Unknown error"));
                    }
                }
            });

            return call;
        } catch (RuntimeException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    callback.onFailure(null, new IOException("Wrong media"));
    return null;
}

From source file:butter.droid.base.youtube.YouTubeData.java

License:Open Source License

/**
 * Calculate the YouTube URL to load the video.  Includes retrieving a token that YouTube
 * requires to play the video.//from   w  w  w.ja v a 2s  .  com
 *
 * @param quality  quality of the video.  17=low, 18=high
 * @param fallback whether to fallback to lower quality in case the supplied quality is not available
 * @param videoId  the id of the video
 * @return the url string that will retrieve the video
 * @throws java.io.IOException
 */
public static String calculateYouTubeUrl(String quality, boolean fallback, String videoId) throws IOException {

    String uriStr = null;
    OkHttpClient client = ButterApplication.getHttpClient();

    Request.Builder request = new Request.Builder();
    request.url(YOUTUBE_VIDEO_INFORMATION_URL + videoId);
    Call call = client.newCall(request.build());
    Response response = call.execute();

    String infoStr = response.body().string();

    String[] args = infoStr.split("&");
    Map<String, String> argMap = new HashMap<String, String>();
    for (String arg : args) {
        String[] valStrArr = arg.split("=");
        if (valStrArr.length >= 2) {
            argMap.put(valStrArr[0], URLDecoder.decode(valStrArr[1]));
        }
    }

    //Find out the URI string from the parameters

    //Populate the list of formats for the video
    String fmtList = URLDecoder.decode(argMap.get("fmt_list"), "utf-8");
    ArrayList<Format> formats = new ArrayList<Format>();
    if (null != fmtList) {
        String formatStrs[] = fmtList.split(",");

        for (String lFormatStr : formatStrs) {
            Format format = new Format(lFormatStr);
            formats.add(format);
        }
    }

    //Populate the list of streams for the video
    String streamList = argMap.get("url_encoded_fmt_stream_map");
    if (null != streamList) {
        String streamStrs[] = streamList.split(",");
        ArrayList<VideoStream> streams = new ArrayList<VideoStream>();
        for (String streamStr : streamStrs) {
            VideoStream lStream = new VideoStream(streamStr);
            streams.add(lStream);
        }

        //Search for the given format in the list of video formats
        // if it is there, select the corresponding stream
        // otherwise if fallback is requested, check for next lower format
        int formatId = Integer.parseInt(quality);

        Format searchFormat = new Format(formatId);
        while (!formats.contains(searchFormat) && fallback) {
            int oldId = searchFormat.getId();
            int newId = getSupportedFallbackId(oldId);

            if (oldId == newId) {
                break;
            }
            searchFormat = new Format(newId);
        }

        int index = formats.indexOf(searchFormat);
        if (index >= 0) {
            VideoStream searchStream = streams.get(index);
            uriStr = searchStream.getUrl();
        }

    }
    //Return the URI string. It may be null if the format (or a fallback format if enabled)
    // is not found in the list of formats for the video
    return uriStr;
}

From source file:ca.zadrox.dota2esportticker.util.MatchDetailLoader.java

License:Apache License

@Override
public Match loadInBackground() {
    try {/*from ww w  .  java  2 s. com*/

        if (mMatch == null) {
            mMatch = new Match();
        }

        OkHttpClient okHttpClient = new OkHttpClient();
        String rawHtml = okHttpClient.newCall(new Request.Builder().url(mUrl).build()).execute().body()
                .string();

        //            try {
        //                trimmedHtml = rawHtml.substring(
        //                    rawHtml.indexOf("<div class=\"box box-match-page\">"),
        //                    rawHtml.indexOf("<div id=\"comments\" class=\"box\">")
        //                );
        //            } catch (StringIndexOutOfBoundsException e) {
        //                LogUtils.LOGD(TAG, "Error fetching match data substring.");
        //                e.printStackTrace();
        //                try {
        //                    trimmedHtml = rawHtml.substring(
        //                        rawHtml.indexOf("<div id=\"col1\" class=\"rows\">"),
        //                        rawHtml.indexOf("<div id=\"col2\" class=\"rows\">")
        //                    );
        //                } catch (StringIndexOutOfBoundsException e1) {
        //                    LogUtils.LOGD(TAG, "Error fetching match data, attempting slow method.");
        //                    e1.printStackTrace();
        //                    // unknown how this will work...
        //                    trimmedHtml = rawHtml;
        //                }
        //            }

        // match basic data

        setupMatchData(rawHtml);

        // gosubet stats

        setupGosubetStats(rawHtml);

        // recent match perf

        setupRecentMatchPerf(rawHtml);

        // livestreams

        setupLivestreamUrls(rawHtml);

        // vods and players present

        setupGamebox(rawHtml);

        // now check steamapi for possible matches of teamnames/players

        return mMatch;

    } catch (IOException e) {
        LogUtils.LOGD(TAG, "Likely no internet reception, or timed out");
        e.printStackTrace();
    } catch (StringIndexOutOfBoundsException e2) {
        LogUtils.LOGD(TAG, "Error fetching match data.");
        e2.printStackTrace();
    }
    return null;
}

From source file:ca.zadrox.dota2esportticker.util.steamapi.SAPIGameResultLoader.java

License:Apache License

/**
 * @return DotaGameData - containing either a FinishedGame, if results were found,
 * NoGameResultData, if no results were found,
 * null, if there's an error with the SAPI.
 *///from ww w. j ava 2  s .c o m
@Override
public DotaGameData loadInBackground() {

    String steamAPIKey = SteamAuth.getSteamApiKey(getContext());

    String getMatchDetailsEndpoint = "http://api.steampowered.com/IDOTA2Match_570/GetMatchDetails/v1/";

    if (mGame == null) {
        mGame = new FinishedGame();
    }

    try {
        OkHttpClient okHttpClient = new OkHttpClient();
        String rawJson = okHttpClient
                .newCall(new Request.Builder()
                        .url(getMatchDetailsEndpoint + "?key=" + steamAPIKey + "&match_id=" + matchId).build())
                .execute().body().string();

        Gson gson = new Gson();

        DotaGameData result = gson.fromJson(rawJson, FinishedGameResult.class).result;

        if (result == null) {
            Log.d(TAG, "returning null...");
            return null;
        } else if (((FinishedGame) result).error != null) {
            return new NoGameResultData();
        } else {
            mGame = result;
            return mGame;
        }

    } catch (IOException e) {
        LOGD(TAG, "Could not grab match json");
    }

    return null;
}

From source file:ca.zadrox.dota2esportticker.util.steamapi.SAPILiveGamesLoader.java

License:Apache License

/**
 * @return DotaGameData[], an array of all live games, if matchId wasn't supplied, or if
 * a matchId was supplied, an array of length 1, containing just the live game specified,
 * or if no games were found, null.//from  w  ww.j  a  va 2  s .  c o m
 */
@Override
public DotaGameData[] loadInBackground() {

    String steamAPIKey = SteamAuth.getSteamApiKey(getContext());

    String getLiveLeagueGamesEndpoint = "http://api.steampowered.com/IDOTA2Match_570/GetLiveLeagueGames/v1/";

    try {
        OkHttpClient okHttpClient = new OkHttpClient();
        String rawJson = okHttpClient.newCall(new Request.Builder().url(getLiveLeagueGamesEndpoint + "?key="
                + steamAPIKey + (matchId != 0 ? "&match_id=" + matchId : "")).build()).execute().body()
                .string();

        if (rawJson.contains("<title>Forbidden</title>")) {
            LocalBroadcastManager.getInstance(getContext())
                    .sendBroadcast(new Intent(SteamAuth.STEAM_API_KEY_INCORRECT));

            return null;
        }

        Gson gson = new Gson();
        try {
            LiveLeagueGames liveLeagueGames = gson.fromJson(rawJson, LiveLeagueGames.class);

            if (liveLeagueGames == null) {
                return null; // no live data.
            } else if (liveLeagueGames.result == null) {
                return null;
            } else if (liveLeagueGames.result.games == null) {
                return null;
            } else if (liveLeagueGames.result.games.length == 0) {
                return null;
            } else {
                mGame = liveLeagueGames.result.games; // return all live games.
                return mGame;
            }
        } catch (RuntimeException e) {
            LogUtils.LOGD(TAG, "Steam Web API is down");
        }

    } catch (IOException e) {
        LogUtils.LOGD(TAG, "Could not grab match json");
    }

    return null;
}

From source file:ca.zadrox.dota2esportticker.util.steamapi.SAPISingleLiveGameLoader.java

License:Apache License

@Override
public DotaGameData loadInBackground() {

    String steamAPIKey = SteamAuth.getSteamApiKey(getContext());

    String getLiveLeagueGamesEndpoint = "http://api.steampowered.com/IDOTA2Match_570/GetLiveLeagueGames/v1/";

    if (mGame == null) {
        mGame = new Game();
    }/* w  w w  . ja  v  a2s . c  om*/

    try {
        OkHttpClient okHttpClient = new OkHttpClient();
        String rawJson = okHttpClient.newCall(new Request.Builder().url(getLiveLeagueGamesEndpoint + "?key="
                + steamAPIKey + (matchId != 0 ? "&match_id=" + matchId : "")).build()).execute().body()
                .string();

        Gson gson = new Gson();

        LiveLeagueGamesResult liveLeagueGames = gson.fromJson(rawJson, LiveLeagueGames.class).result;

        if (liveLeagueGames == null || liveLeagueGames.games == null || liveLeagueGames.games.length == 0) {
            return null; // game has concluded, return null and handle appropriately.
        } else {
            mGame = liveLeagueGames.games[0];
            return mGame;
        }

    } catch (IOException e) {
        LogUtils.LOGD(TAG, "Could not grab match json");
    }

    return null;
}

From source file:ca.zadrox.dota2esportticker.util.TeamDetailLoader.java

License:Apache License

@Override
public Team loadInBackground() {

    if (mTeam == null) {
        mTeam = new Team();
    }/*from  www. j a  va 2s  .com*/

    String rawHtml;

    try {
        OkHttpClient okHttpClient = new OkHttpClient();
        rawHtml = okHttpClient.newCall(new Request.Builder().url(mUrl).build()).execute().body().string();
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

    // teamCountry + socialMedia + logo + name

    int start = rawHtml.indexOf("<div class=\"titleTeamHolderGG\">");
    int end = rawHtml.indexOf("<div class=\"teamInfoHolder\">");

    String sec = rawHtml.substring(start, end);

    Document doc = Jsoup.parse(sec);

    mTeam.name = doc.getElementsByTag("h1").first().text();
    mTeam.name = mTeam.name.substring(0, mTeam.name.indexOf(" - Team Overview"));
    mTeam.name = mTeam.name.replaceAll(" ?\\.?\\-?-?Dot[aA][\\s]?2", "");

    String logoUrl = doc.getElementsByClass("teamImage").attr("style");
    logoUrl = BASE_URL + logoUrl.substring(logoUrl.indexOf("/uploads"), logoUrl.length() - 2);

    try {

        mTeam.logo = Picasso.with(getContext()).load(logoUrl).get();

        mTeam.palette = Palette.generate(mTeam.logo);

    } catch (IOException e) {
        LogUtils.LOGD(TAG, "Did not generate palette");
        e.printStackTrace();
    }

    mTeam.country = doc.getElementsByClass("flag").first().attr("title");

    ArrayList<SocialMedia> socialMedia = new ArrayList<>();

    for (Element element : doc.getElementsByClass("social").first().getElementsByTag("a")) {
        SocialMedia temp = new SocialMedia();
        temp.socialUrl = element.attr("href");
        temp.socialType = element.child(0).attr("title");
        socialMedia.add(temp);
    }

    mTeam.socialMedia = socialMedia.toArray(new SocialMedia[socialMedia.size()]);

    // teamRankings

    start = rawHtml.indexOf("<div class=\"teamInfoHolder\">", end);
    end = rawHtml.indexOf("<div class=\"statistics\">", start);

    if (!(start == -1 || end == -1)) {

        sec = rawHtml.substring(start, end);

        doc = Jsoup.parse(sec);

        ArrayList<Ranking> teamRankings = new ArrayList<>();

        for (Element element : doc.getElementsByClass("ranking")) {
            Ranking temp = new Ranking();
            temp.ranking = element.getElementsByClass("number").first().text();
            temp.region = element.getElementsByClass("region").first().text();
            teamRankings.add(temp);
        }

        mTeam.rankings = teamRankings.toArray(new Ranking[teamRankings.size()]);

    }

    // teamStatistics + currentStreak

    start = rawHtml.indexOf("<div class=\"statistics\">", end);
    end = rawHtml.indexOf("<div class=\"roster clearfix\">", start);

    if (!(start == -1 || end == -1)) {

        sec = rawHtml.substring(start, end);

        doc = Jsoup.parse(sec);

        ArrayList<Statistic> teamStatistics = new ArrayList<>();

        Elements tableSections = doc.getElementsByTag("tr");
        // these start from 1.
        Elements timeframes = tableSections.get(0).getElementsByTag("th");
        Elements winrates = tableSections.get(1).getElementsByTag("td");
        Elements matchesPlayed = tableSections.get(2).getElementsByTag("td");

        for (int i = 0; i < 3; i++) {
            Statistic temp = new Statistic();
            temp.timeFrame = timeframes.get(i + 1).text();
            temp.winPercentage = winrates.get(i).text();
            Elements scores = matchesPlayed.get(i).getElementsByTag("span");
            temp.wonMatches = scores.get(0).text();
            temp.tiedMatches = scores.get(1).text();
            temp.lostMatches = scores.get(2).text();

            teamStatistics.add(temp);
        }

        mTeam.statistics = teamStatistics.toArray(new Statistic[teamStatistics.size()]);
        mTeam.currentStreak = tableSections.get(3).getElementsByTag("td").text();

    }

    // Roster

    start = rawHtml.indexOf("<div class=\"roster clearfix\">", end);
    end = rawHtml.indexOf("<div class=\"performance\">", start);

    if (!(start == -1 || end == -1)) {

        sec = rawHtml.substring(start, end);

        doc = Jsoup.parse(sec);

        ArrayList<Player> teamRoster = new ArrayList<>();
        String ggUrlPrefix = "http://www.gosugamers.net/dota2/";

        Elements players = doc.getElementsByTag("a");

        for (Element player : players) {
            Player temp = new Player();
            temp.profileUrl = ggUrlPrefix + player.attr("href");
            String unprocessedProfPic = player.getElementsByClass("image").attr("style");
            temp.profilePicUrl = BASE_URL + unprocessedProfPic.substring(unprocessedProfPic.indexOf("/uploads"),
                    unprocessedProfPic.length() - 3);
            temp.country = player.getElementsByTag("span").first().attr("title");
            temp.gameAlias = player.getElementsByTag("h5").first().text();
            temp.realName = player.getElementsByTag("span").get(1).text();

            if (!player.getElementsByClass("heroes").first().text().contains("Manager")) {
                teamRoster.add(temp);
            }
        }

        mTeam.roster = teamRoster.toArray(new Player[teamRoster.size()]);

    }

    // Upcoming Matches

    start = rawHtml.indexOf("<table id=\"gb-matches\" class=\"simple gamelist clearbottom\">", end);
    end = rawHtml.indexOf("<div id=\"box-ad\" class=\"ad\">", start) - 12;

    if (!(start == -1 || end == -1)) {

        sec = rawHtml.substring(start, end);

        doc = Jsoup.parse(sec);

        ArrayList<String> upcomingMatchUrls = new ArrayList<>();

        Elements upcomingMatches = doc.getElementsByTag("a");

        for (Element uMatch : upcomingMatches) {
            upcomingMatchUrls.add(BASE_URL + uMatch.attr("href"));
        }

        mTeam.upcomingMatches = upcomingMatchUrls.toArray(new String[upcomingMatchUrls.size()]);

        // Recent Matches

        start = rawHtml.indexOf("<div class=\"graph-wrap\">", end);
        end = rawHtml.indexOf("<div id=\"box-ad\" class=\"ad\">", start);

        sec = rawHtml.substring(start, end);

        doc = Jsoup.parse(sec);

        ArrayList<String> recentMatchUrls = new ArrayList<>();

        Elements recentMatches = doc.getElementsByClass("match-list-row");

        for (Element rMatch : recentMatches) {
            recentMatchUrls.add(BASE_URL + rMatch.getElementsByTag("a").first().attr("href"));
        }

        mTeam.recentMatches = recentMatchUrls.toArray(new String[recentMatchUrls.size()]);

    }

    // Achievements

    start = rawHtml.indexOf("<div class=\"content\">", end);
    end = rawHtml.indexOf("<div id=\"lower-lb-ad\">", start);

    if (!(start == -1 || end == -1)) {

        sec = rawHtml.substring(start, end);
        //sec = sec.replace("<br/>", " : ");

        doc = Jsoup.parse(sec);

        Elements achievements = doc.getElementsByTag("p");

        ArrayList<Achievement> achieveList = new ArrayList<>();

        for (int i = 0; i < achievements.size(); i++) {
            Element achievementBlock = achievements.get(i);
            String check = achievementBlock.text().substring(0,
                    achievementBlock.text().length() >= 12 ? 12 : 0);

            if (check.equals("Achievements")) {
                i++;
                String[] mEvents = achievements.get(i).html().split("<br>");

                for (String event : mEvents) {
                    Achievement temp = new Achievement();
                    Document document = Jsoup.parse(event);

                    temp.place = document.getElementsByTag("body").first().child(0).text();
                    temp.place = temp.place.replaceAll("(\\s?-\\s?$)|(\\s$)", "");

                    try {
                        Element tournamentInfo = document.getElementsByTag("a").first();
                        temp.tournament = tournamentInfo.text();
                        temp.tournamentUrl = tournamentInfo.attr("href");
                    } catch (NullPointerException e) {
                        LogUtils.LOGD(TAG, "No <a>, fallback method");
                    }

                    if (temp.tournament == null) {
                        temp.tournament = document.getElementsByTag("body").first().textNodes().get(0).text();
                        temp.tournament = temp.tournament.replaceAll("(^\\s?-\\s?)|(\\s?-\\s?$)|(\\s$)", "");
                    }

                    temp.year = document.getElementsByTag("em").first().text();
                    temp.year = temp.year.substring(temp.year.indexOf('(') + 1, temp.year.indexOf(')'));

                    String text = document.getElementsByTag("body").first().text();
                    int startIndex = text.indexOf(temp.tournament) + temp.tournament.length();
                    //LogUtils.LOGD(TAG, "startIndex: " + startIndex);
                    int endIndex = text.indexOf("- ", startIndex);
                    if (endIndex == -1) {
                        temp.prizeReward = "No Reward";
                    } else {
                        temp.prizeReward = text.substring(endIndex + 2);
                    }

                    achieveList.add(temp);
                }
            }
        }

        mTeam.achievements = achieveList.toArray(new Achievement[achieveList.size()]);
    }

    return mTeam;
}

From source file:client.lib.Client.java

private Response request(OkHttpClient client, URL url) {
    Response response = null;//from w w  w .ja v a2s.c o m

    try {
        System.out.println(client.getProtocols().get(0) + " => " + url.toString());

        Request request = new Request.Builder().url(url.toString()).build();
        response = client.newCall(request).execute();

        System.out.println("> " + response.code() + " " + response.protocol());

    } catch (ConnectException e) {
        System.out.println("ConnectException: " + e.getMessage());
    } catch (IOException e) {
        System.out.println("IOException: " + e.getMessage());
    }

    return response;
}

From source file:client.ui.Container.java

private Response request(OkHttpClient client, URL url, String json) {
    Response response = null;/*from   www .ja v  a2s.  c o  m*/

    try {
        log("Requesting: " + client.getProtocols().get(0) + " => " + url.toString());

        Builder builder = new Request.Builder().url(url.toString());
        if (!"".equals(json)) {
            builder.post(RequestBody.create(MediaType.parse("application/json"), json));
        }
        Request request = builder.build();

        response = client.newCall(request).execute();

        log("Completed: " + response.code());

    } catch (ConnectException e) {
        log("\n" + "Failed: " + e.getMessage());
    } catch (IOException e) {
        log("Failed: " + e.getMessage());
    }

    return response;
}