List of usage examples for com.squareup.okhttp OkHttpClient OkHttpClient
public OkHttpClient()
From source file:br.org.cesar.knot.lib.connection.ThingApi.java
License:Open Source License
public ThingApi(String endPoint, String owner_uuid, String owner_token) { mMainHandler = new Handler(Looper.getMainLooper()); mHttpClient = new OkHttpClient(); mGson = new Gson(); mEndPoint = endPoint;//from w ww . j a v a 2 s .c om abstractDeviceOwner = new AbstractDeviceOwner(); abstractDeviceOwner.setUuid(owner_uuid); abstractDeviceOwner.setToken(owner_token); }
From source file:butter.droid.base.ButterApplication.java
License:Open Source License
public static OkHttpClient getHttpClient() { if (sHttpClient == null) { sHttpClient = new OkHttpClient(); sHttpClient.setConnectTimeout(30, TimeUnit.SECONDS); sHttpClient.setReadTimeout(60, TimeUnit.SECONDS); sHttpClient.setRetryOnConnectionFailure(true); int cacheSize = 10 * 1024 * 1024; File cacheLocation = new File(PrefUtils.get(ButterApplication.getAppContext(), Prefs.STORAGE_LOCATION, StorageUtils.getIdealCacheDirectory(ButterApplication.getAppContext()).toString())); cacheLocation.mkdirs();/* www .j av a 2s. c o m*/ com.squareup.okhttp.Cache cache = null; try { cache = new com.squareup.okhttp.Cache(cacheLocation, cacheSize); } catch (Exception e) { e.printStackTrace(); } sHttpClient.setCache(cache); } return sHttpClient; }
From source file:ca.mymenuapp.data.DataModule.java
License:Open Source License
static OkHttpClient createOkHttpClient(Context app) { OkHttpClient client = new OkHttpClient(); // Install an HTTP cache in the application cache directory. try {//w w w . java 2 s. c o m File cacheDir = new File(app.getCacheDir(), "http"); HttpResponseCache cache = new HttpResponseCache(cacheDir, DISK_CACHE_SIZE); client.setResponseCache(cache); } catch (IOException e) { Ln.e(e, "Unable to install disk cache."); } return client; }
From source file:ca.zadrox.dota2esportticker.service.UpdateMatchService.java
License:Apache License
private void updateMatches(boolean doResults) { if (!checkForConnectivity()) { LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(UPDATE_NO_CONNECTIVITY)); return;/* www . ja va2s. c o m*/ } LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(UPDATE_STARTED)); final String BASE_URL = "http://www.gosugamers.net/dota2/gosubet"; final String MATCH_LINK_URL_BASE = "http://www.gosugamers.net"; try { String rawHtml = new OkHttpClient().newCall(new Request.Builder().url(BASE_URL).build()).execute() .body().string(); rawHtml = rawHtml.substring(rawHtml.indexOf("<div id=\"col1\" class=\"rows\">"), rawHtml.indexOf("<div id=\"col2\" class=\"rows\">")); Document doc = Jsoup.parse(rawHtml); Elements tables = doc.getElementsByClass("matches"); ArrayList<ArrayList<String>> matchLinks = new ArrayList<ArrayList<String>>(tables.size()); int numSeries = 0; for (Element table : tables) { Elements links = table.getElementsByClass("match"); if (links.size() != 0) { ArrayList<String> innerMatchLink = new ArrayList<String>(links.size()); for (Element link : links) { String linkHref = link.attr("href"); innerMatchLink.add(MATCH_LINK_URL_BASE + linkHref); numSeries++; } matchLinks.add(innerMatchLink); } } // needed if there are massive reschedules to update content properly. Uri resultsUri = MatchContract.SeriesEntry.buildSeriesUriWithAfterTime(TimeUtils.getUTCTime()); Cursor c = getContentResolver().query(resultsUri, new String[] { MatchContract.SeriesEntry.COLUMN_GG_MATCH_PAGE }, null, null, null); while (c.moveToNext()) { if (!matchLinks.get(0).contains(c.getString(0))) { matchLinks.get(0).add(c.getString(0)); } } Iterator<ArrayList<String>> iterator = matchLinks.iterator(); int numResults = 0; ExecutorService executorService = Executors.newFixedThreadPool(10); ArrayList<Future<BundledMatchItem>> seriesItemFutures = new ArrayList<Future<BundledMatchItem>>( numSeries); LogUtils.LOGD(TAG, "Starting Retrieval, num elements gathered: " + numSeries); int i = 0; while (iterator.hasNext()) { ArrayList<String> matchList = iterator.next(); for (String matchUrl : matchList) { boolean hasResult = !iterator.hasNext(); if (!doResults && hasResult) { continue; } else if (hasResult) { numResults++; } seriesItemFutures.add(executorService.submit(new MatchGetter(matchUrl, hasResult))); i++; } } executorService.shutdown(); executorService.awaitTermination(20L, TimeUnit.SECONDS); LogUtils.LOGD(TAG, "Stopping Retrieval, elements submitted for fetching: " + i); ContentValues[] seriesEntries = new ContentValues[i]; ContentValues[] resultEntries = new ContentValues[numResults]; int seriesEntryWriteIndex = 0; int resultEntryWriteIndex = 0; for (Future<BundledMatchItem> seriesItemFuture : seriesItemFutures) { try { BundledMatchItem seriesItem = seriesItemFuture.get(); if (seriesItem != null) { seriesEntries[seriesEntryWriteIndex] = seriesItem.mMatch; seriesEntryWriteIndex++; if (seriesItem.hasResult) { resultEntries[resultEntryWriteIndex] = seriesItem.mResult; resultEntryWriteIndex++; } } } catch (ExecutionException e) { Log.e(TAG, "Should never get here"); } } this.getContentResolver().bulkInsert(MatchContract.SeriesEntry.CONTENT_URI, seriesEntries); if (doResults) this.getContentResolver().bulkInsert(MatchContract.ResultEntry.CONTENT_URI, resultEntries); PrefUtils.setLastUpdateTime(this, TimeUtils.getUTCTime()); } catch (IOException e) { Log.e(TAG, e.getMessage(), e); e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(UPDATE_COMPLETE)); PrefUtils.setLastResultsUpdateTime(this, TimeUtils.getUTCTime()); }
From source file:ca.zadrox.dota2esportticker.service.UpdateTeamsService.java
License:Apache License
private void updateTopTeams() { LOGD(TAG, "starting update"); // actually, first, check for connectivity: if (!checkForConnectivity()) { LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_NO_CONNECTIVITY)); LOGD(TAG, "returning due to no connectivity"); return;/* w w w. j ava2 s.c o m*/ } // first, check last update time long lastUpdate = PrefUtils.lastTeamsUpdate(this); long currentTime = TimeUtils.getUTCTime(); // if last update is less than 1 hour old, boot user to cursorloader op. if (currentTime - lastUpdate < 60000 * 60) { LOGD(TAG, "returnning due to too soon"); LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_COMPLETED)); return; } // else // use local broadcast manager to show loading indicator LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_UPDATING)); final String BASE_URL = "http://www.gosugamers.net/dota2/rankings"; final String TEAM_LINK_BASE_URL = "http://www.gosugamers.net/dota2/teams/"; // we see what teams are in top 50. (httpreq -> gosugamers) try { String rawHtml = new OkHttpClient().newCall(new Request.Builder().url(BASE_URL).build()).execute() .body().string(); String processedHtml = rawHtml.substring(rawHtml.indexOf("<div id=\"col1\" class=\"rows\">"), rawHtml.indexOf("<div id=\"col2\" class=\"rows\">")); Elements teamRows = Jsoup.parse(processedHtml).getElementsByClass("ranking-link"); ExecutorService executorService = Executors.newFixedThreadPool(10); ContentValues[] teamRanks = new ContentValues[50]; HashMap<ContentValues, Future<String>> newTeamInfo = new HashMap<ContentValues, Future<String>>(); HashMap<ContentValues, Future<String>> updateTeamInfo = new HashMap<ContentValues, Future<String>>(); int i = 0; for (Element teamRow : teamRows) { ContentValues contentValues = new ContentValues(); String teamId = teamRow.attr("data-id"); contentValues.put(MatchContract.TeamEntry._ID, teamId); String untrimmedTeamName = teamRow.getElementsByTag("h4").first().text(); String teamUrl = TEAM_LINK_BASE_URL + teamId + "-" + untrimmedTeamName.replaceAll("[\\W]?[\\W][\\W]*", "-").toLowerCase(); contentValues.put(MatchContract.TeamEntry.COLUMN_TEAM_URL, teamUrl); String teamName = untrimmedTeamName.replaceAll(" ?\\.?\\-?-?Dot[aA][\\s]?2", ""); contentValues.put(MatchContract.TeamEntry.COLUMN_TEAM_NAME, teamName); if (teamUrl.charAt(teamUrl.length() - 1) == '-') { teamUrl = teamUrl.substring(0, teamUrl.length() - 2); } // then, we query db for id of the team ( Cursor cursor = getContentResolver().query( MatchContract.TeamEntry.buildTeamUri(Long.parseLong(teamId)), new String[] { MatchContract.TeamEntry.COLUMN_TEAM_NAME, MatchContract.TeamEntry.COLUMN_TEAM_URL }, null, null, null); // -> if present, and data remains unchanged, continue. // -> if present, but data is changed, add to update queue. if (cursor.moveToFirst()) { LOGD(TAG, "Have team already?"); if (!cursor.getString(0).contentEquals(teamName) || !cursor.getString(1).contentEquals(teamUrl)) { LOGD(TAG, "Team has updated values."); updateTeamInfo.put(contentValues, executorService.submit(new TeamGetter(teamUrl))); } } // -> if not present, add to update queue. else { LOGD(TAG, "Do team update"); newTeamInfo.put(contentValues, executorService.submit(new TeamGetter(teamUrl))); } // LOGD(TAG, "\n" + // "data-id: " + teamId + "\n" + // "team-name: " + teamName + "\n" + // "team-url: " + teamUrl); teamRanks[i] = new ContentValues(); teamRanks[i].put(MatchContract.TeamRankEntry._ID, i + 1); teamRanks[i].put(MatchContract.TeamRankEntry.COLUMN_TEAM_ID, teamId); cursor.close(); i++; } executorService.shutdown(); executorService.awaitTermination(20, TimeUnit.SECONDS); for (ContentValues contentValues : newTeamInfo.keySet()) { try { String teamLogo = newTeamInfo.get(contentValues).get(); contentValues.put(MatchContract.TeamEntry.COLUMN_TEAM_LOGO_URL, teamLogo); } catch (ExecutionException e) { LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_ERROR)); e.printStackTrace(); } } for (ContentValues contentValues : updateTeamInfo.keySet()) { try { String teamLogo = updateTeamInfo.get(contentValues).get(); contentValues.put(MatchContract.TeamEntry.COLUMN_TEAM_LOGO_URL, teamLogo); String teamId = contentValues.getAsString(MatchContract.TeamEntry._ID); contentValues.remove(MatchContract.TeamEntry._ID); int updatedRows = getContentResolver().update(MatchContract.TeamEntry.CONTENT_URI, contentValues, MatchContract.TeamEntry.TABLE_NAME + "." + MatchContract.TeamEntry._ID + " = ?", new String[] { teamId }); LOGD(TAG, "updatedRows: " + updatedRows); } catch (ExecutionException e) { LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_ERROR)); e.printStackTrace(); } } getContentResolver().bulkInsert(MatchContract.TeamEntry.CONTENT_URI, newTeamInfo.keySet().toArray(new ContentValues[newTeamInfo.size()])); getContentResolver().bulkInsert(MatchContract.TeamRankEntry.CONTENT_URI, teamRanks); } catch (IOException e) { LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_ERROR)); e.printStackTrace(); } catch (InterruptedException e2) { LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_ERROR)); e2.printStackTrace(); } // String[] projection = new String[]{ // MatchContract.TeamEntry.TABLE_NAME + "." + MatchContract.TeamEntry._ID, // MatchContract.TeamEntry.COLUMN_TEAM_NAME, // MatchContract.TeamEntry.COLUMN_TEAM_URL, // MatchContract.TeamEntry.COLUMN_TEAM_LOGO_URL, // MatchContract.TeamEntry.COLUMN_TEAM_STARRED, // MatchContract.TeamRankEntry.TABLE_NAME + "." + MatchContract.TeamRankEntry._ID // }; // // String sortOrder = // MatchContract.TeamRankEntry.TABLE_NAME + "." + // MatchContract.TeamRankEntry._ID + " ASC"; // // Cursor c = getContentResolver().query( // MatchContract.TeamEntry.TOP_50_URI, // projection, // null, // null, // sortOrder // ); // // while (c.moveToNext()) { // String teamPrintOut = // "Rank: " + c.getInt(5) + "\n" + // "teamId: " + c.getInt(0) + " teamName: " + c.getString(1) + "\n" + // "teamUrl: " + c.getString(2) + "\n" + // "teamLogoUrl: " + c.getString(3) + "\n" + // "isFavourited: " + (c.getInt(4) == 0 ? "false" : "true"); // LOGD(TAG + "/UTT", teamPrintOut); // } // // c.close(); // use local broadcast manager to hide loading indicator // and signal that cursorloader for top50 can happen. PrefUtils.setLastTeamUpdate(this, currentTime); LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_COMPLETED)); }
From source file:ca.zadrox.dota2esportticker.service.UpdateTeamsService.java
License:Apache License
private void updateSearchedTeams(String searchName) { LOGD(TAG, "starting search update"); // actually, first, check for connectivity: if (!checkForConnectivity()) { LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_NO_CONNECTIVITY)); LOGD(TAG, "returning due to no connectivity"); return;//from w ww . ja v a2 s .co m } LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_UPDATING)); final String BASE_URL = "http://www.gosugamers.net/dota2/rankings" + "?tname=" + searchName.replace(' ', '+') + "&tunranked=0#team"; final String TEAM_LINK_BASE_URL = "http://www.gosugamers.net/dota2/teams/"; try { String rawHtml = new OkHttpClient().newCall(new Request.Builder().url(BASE_URL).build()).execute() .body().string(); String processedHtml = rawHtml.substring(rawHtml.indexOf("<div id=\"col1\" class=\"rows\">"), rawHtml.indexOf("<div id=\"col2\" class=\"rows\">")); Elements teamRows = Jsoup.parse(processedHtml).getElementsByClass("ranking-link"); ExecutorService executorService = Executors.newFixedThreadPool(10); HashMap<ContentValues, Future<String>> newTeamInfo = new HashMap<ContentValues, Future<String>>(); HashMap<ContentValues, Future<String>> updateTeamInfo = new HashMap<ContentValues, Future<String>>(); for (Element teamRow : teamRows) { ContentValues contentValues = new ContentValues(); String teamId = teamRow.attr("data-id"); contentValues.put(MatchContract.TeamEntry._ID, teamId); String untrimmedTeamName = teamRow.getElementsByTag("h4").first().text(); String teamUrl = TEAM_LINK_BASE_URL + teamId + "-" + untrimmedTeamName.replaceAll("[\\W]?[\\W][\\W]*", "-").toLowerCase(); contentValues.put(MatchContract.TeamEntry.COLUMN_TEAM_URL, teamUrl); String teamName = untrimmedTeamName.replaceAll(" ?\\.?\\-?-?Dot[aA][\\s]?2", ""); contentValues.put(MatchContract.TeamEntry.COLUMN_TEAM_NAME, teamName); if (teamUrl.charAt(teamUrl.length() - 1) == '-') { teamUrl = teamUrl.substring(0, teamUrl.length() - 2); } // then, we query db for id of the team ( Cursor cursor = getContentResolver().query( MatchContract.TeamEntry.buildTeamUri(Long.parseLong(teamId)), new String[] { MatchContract.TeamEntry.COLUMN_TEAM_NAME, MatchContract.TeamEntry.COLUMN_TEAM_URL }, null, null, null); // -> if present, and data remains unchanged, continue. // -> if present, but data is changed, add to update queue. if (cursor.moveToFirst()) { LOGD(TAG, "Team in DB, determining if values need updating"); if (!cursor.getString(0).contentEquals(teamName) || !cursor.getString(1).contentEquals(teamUrl)) { LOGD(TAG, "Team has updated values, double checking logo & writing to DB"); updateTeamInfo.put(contentValues, executorService.submit(new TeamGetter(teamUrl))); } } // -> if not present, add to update queue. else { LOGD(TAG, "Team not in DB. Grabbing logo & writing to DB"); newTeamInfo.put(contentValues, executorService.submit(new TeamGetter(teamUrl))); } // LOGD(TAG, "\n" + // "data-id: " + teamId + "\n" + // "team-name: " + teamName + "\n" + // "team-url: " + teamUrl); // cursor.close(); } executorService.shutdown(); executorService.awaitTermination(20, TimeUnit.SECONDS); for (ContentValues contentValues : newTeamInfo.keySet()) { try { String teamLogo = newTeamInfo.get(contentValues).get(); contentValues.put(MatchContract.TeamEntry.COLUMN_TEAM_LOGO_URL, teamLogo); } catch (ExecutionException e) { LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_ERROR)); e.printStackTrace(); } } for (ContentValues contentValues : updateTeamInfo.keySet()) { try { String teamLogo = newTeamInfo.get(contentValues).get(); contentValues.put(MatchContract.TeamEntry.COLUMN_TEAM_LOGO_URL, teamLogo); String teamId = contentValues.getAsString(MatchContract.TeamEntry._ID); contentValues.remove(MatchContract.TeamEntry._ID); int updatedRows = getContentResolver().update(MatchContract.TeamEntry.CONTENT_URI, contentValues, MatchContract.TeamEntry.TABLE_NAME + "." + MatchContract.TeamEntry._ID + " = ?", new String[] { teamId }); LOGD(TAG, "updatedRows: " + updatedRows); } catch (ExecutionException e) { LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_ERROR)); e.printStackTrace(); } } getContentResolver().bulkInsert(MatchContract.TeamEntry.CONTENT_URI, newTeamInfo.keySet().toArray(new ContentValues[newTeamInfo.size()])); } catch (IOException e) { LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_ERROR)); e.printStackTrace(); } catch (InterruptedException e2) { LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_ERROR)); e2.printStackTrace(); } // String[] projection = new String[]{ // MatchContract.TeamEntry.TABLE_NAME + "." + MatchContract.TeamEntry._ID, // MatchContract.TeamEntry.COLUMN_TEAM_NAME, // MatchContract.TeamEntry.COLUMN_TEAM_URL, // MatchContract.TeamEntry.COLUMN_TEAM_LOGO_URL, // MatchContract.TeamEntry.COLUMN_TEAM_STARRED, // }; // // String sortOrder = // MatchContract.TeamEntry.COLUMN_TEAM_NAME + " ASC"; // // Cursor c = getContentResolver().query( // MatchContract.TeamEntry.CONTENT_URI, // projection, // MatchContract.TeamEntry.COLUMN_TEAM_NAME + " LIKE '%" + searchName + "%'", // null, // sortOrder // ); // // LOGD(TAG+"/UST", "Starting Printout: "); // int i = 0; // while (c.moveToNext()) { // String teamPrintOut = // "teamId: " + c.getInt(0) + " teamName: " + c.getString(1) + "\n" + // "teamUrl: " + c.getString(2) + "\n" + // "teamLogoUrl: " + c.getString(3) + "\n" + // "isFavourited: " + (c.getInt(4) == 0 ? "false" : "true"); // LOGD(TAG + "/UST", teamPrintOut); // i++; // } // LOGD(TAG+"/UST", "Stopping Printout. Count: " + i); // // c.close(); // use local broadcast manager to hide loading indicator // and signal that cursorloader for top50 can happen. LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_COMPLETED)); }
From source file:ca.zadrox.dota2esportticker.util.MatchDetailLoader.java
License:Apache License
@Override public Match loadInBackground() { try {// www . j a v a 2 s.c o m 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.MatchGetter.java
License:Apache License
@Override public BundledMatchItem call() { try {/*from ww w .j a v a 2s . c o m*/ String lastPathSegment = Uri.parse(matchUrl).getLastPathSegment(); long matchId = Long.parseLong(lastPathSegment.substring(0, lastPathSegment.indexOf("-"))); String rawHtml = new OkHttpClient().newCall(new Request.Builder().url(matchUrl).build()).execute() .body().string(); String processedHtml = ""; processedHtml += rawHtml.substring(rawHtml.indexOf("<div class=\"box box-match-page\">"), rawHtml.indexOf("<div class=\"content\">")); processedHtml += rawHtml.substring(rawHtml.indexOf("<div class=\"ad event-ad\">"), rawHtml.indexOf("<a class=\"howto-itembet\"")); try { processedHtml += rawHtml.substring(rawHtml.indexOf("<div class=\"match-opponents\">"), rawHtml.indexOf("<div id=\"betting-tabs\" ")); } catch (IndexOutOfBoundsException e) { LOGD(TAG, "Page does not have betting tabs. Attempting to use comment section"); try { processedHtml += rawHtml.substring(rawHtml.indexOf("<div class=\"match-opponents\">"), rawHtml.indexOf("<div id=\"comments\" ")); } catch (IndexOutOfBoundsException e2) { LOGE(TAG, "Well, not sure what next to substring then..."); } } Document doc = Jsoup.parse(processedHtml); if (!mHasResult) { return new BundledMatchItem(parseMatchDetails(doc, matchId)); } else { return new BundledMatchItem(parseMatchDetails(doc, matchId), parseResultDetails(doc, matchId)); } } catch (Exception e) { Log.e(TAG, "WHAT. " + matchUrl); e.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. *///www . j a va2 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 w w . ja v a 2 s . c om*/ */ @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; }