Example usage for com.squareup.okhttp OkHttpClient OkHttpClient

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

Introduction

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

Prototype

public OkHttpClient() 

Source Link

Usage

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();
    }/*from   ww  w . ja v a  2 s .  co m*/

    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();
    }//  ww w. ja  v  a 2  s  .  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:ca.zadrox.dota2esportticker.util.TeamGetter.java

License:Apache License

@Override
public String call() {
    try {/*from w  w  w. jav a 2 s .com*/
        String rawHtml = new OkHttpClient().newCall(new Request.Builder().url(teamUrl).build()).execute().body()
                .string();

        String processedHtml = rawHtml.substring(
                rawHtml.indexOf("<div class=\"teamImage\" style=\"background-image: url('") + 53,
                rawHtml.indexOf("<div class=\"teamNameHolder\">") - 11);

        LOGD(TAG, processedHtml);
        return BASE_URL + processedHtml;

    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:cat.ppicas.cleanarch.app.DefaultServiceContainer.java

License:Apache License

private OkHttpClient getOkHttpClient() {
    if (mOkClient == null) {
        mOkClient = new OkHttpClient();
        mOkClient.setConnectTimeout(10, TimeUnit.SECONDS);
        mOkClient.setReadTimeout(5, TimeUnit.SECONDS);
        mOkClient.setWriteTimeout(5, TimeUnit.SECONDS);
        mOkClient.setCache(createOkHttpCache());
    }//from   w ww  .j  a v  a 2  s. com

    return mOkClient;
}

From source file:cl.magnet.magnetrestclient.VolleyManager.java

License:Open Source License

/**
 * Returns the singleton instance of RequestQueue that last the lifetime of the app. If there
 * is no instance of RequestQueue, then a new one is created.
 * <p/>//from   www  .ja va2  s . c  o  m
 * The created RequestQueue uses {@link cl.magnet.magnetrestclient.OkHttpStack OkHttpStack}
 * for networking.
 *
 * @return RequestQueue instance
 */
private RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
        // getApplicationContext() keeps from leaking Activity or BroadcastReceiver if
        // someone pass one in
        OkHttpClient client = new OkHttpClient();
        client.setCookieHandler(CookieHandler.getDefault());
        mRequestQueue = Volley.newRequestQueue(mContext.getApplicationContext(), new OkHttpStack(client));
    }

    return mRequestQueue;
}

From source file:client.lib.Client.java

public Client() throws NoSuchAlgorithmException, KeyManagementException {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            X509Certificate[] myTrustedAnchors = new X509Certificate[0];
            return myTrustedAnchors;
        }/*from   w w w . j  a v a 2  s.c  o  m*/

        @Override
        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] certs, String authType) {
        }
    } };

    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, trustAllCerts, new SecureRandom());

    // Create an ssl socket factory with our all-trusting manager
    final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

    http2Client = new OkHttpClient();
    http2Client.setSslSocketFactory(sslSocketFactory);
    http2Client.setHostnameVerifier(new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    });

    httpClient = http2Client.clone();

    httpClient.setProtocols(Arrays.asList(Protocol.HTTP_1_1));
    http2Client.setProtocols(Arrays.asList(Protocol.HTTP_2));
}

From source file:client.ui.Container.java

private void initClients() {
    http2Client = new OkHttpClient();
    httpClient = http2Client.clone();//from  w  w w  .j  a  v  a 2  s  . com

    httpClient.setProtocols(Arrays.asList(Protocol.HTTP_1_1));
    http2Client.setProtocols(Arrays.asList(Protocol.HTTP_2));
}

From source file:cn.finalteam.okhttpfinal.OkHttpFactory.java

License:Apache License

public static OkHttpClient getOkHttpClientFactory(long timeout) {
    OkHttpClient client = new OkHttpClient();
    ///*w  ww  .j a v a  2s  . co m*/
    client.setConnectTimeout(timeout, TimeUnit.MILLISECONDS);
    client.setWriteTimeout(timeout, TimeUnit.MILLISECONDS);
    client.setReadTimeout(timeout, TimeUnit.MILLISECONDS);
    //???
    client.setRetryOnConnectionFailure(false);
    //???
    client.setFollowRedirects(true);
    //?cookie
    client.setCookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ORIGINAL_SERVER));

    return client;
}

From source file:cn.garymb.wechatmoments.model.Model.java

License:Apache License

private Model(StaticApplication app) {
    mBundlePool = new ParcelableObjectPool(new ParcelablePoolObjectFactory(), MAX_BUNDLE_FACTORY_SIZE);
    DataExecutors executors = new DataExecutors(
            Volley.newRequestQueue(app, new OkHttpStack(new OkHttpClient())));
    mImageModelHelper = new ImageModelHelper(executors);
    mDataModelHelper = new DataModelHelper(executors);
}

From source file:cn.net.xyd.utils.VolleyHelper.java

License:Apache License

/**
 * init volley helper/*  w w  w . j  a  v  a2s. co  m*/
 *
 * @param context
 */
public void init(Context context) {
    requestQueue = Volley.newRequestQueue(context, new OkHttpStack(new OkHttpClient()));
}