Skip to content

Instantly share code, notes, and snippets.

@adriantache
Created July 14, 2019 13:41
Show Gist options
  • Save adriantache/198e5beab6960d8cf384f11dc8ec60d0 to your computer and use it in GitHub Desktop.
Save adriantache/198e5beab6960d8cf384f11dc8ec60d0 to your computer and use it in GitHub Desktop.
//First we build the URI and the auth header and pass them to the AsyncTask
private static final String GIT_HUB_API = "api.github.com";
private static final String USER_ENDPOINT = "user";
private static final String REPOS_ENDPOINT = "repos";
private static final String ERROR = "error";
//(...)
Uri.Builder builder = new Uri.Builder();
builder.scheme("https")
.authority(GIT_HUB_API)
.appendPath(USER_ENDPOINT)
.appendPath(REPOS_ENDPOINT);
//this is how we build the Basic Authentication header contents
String base = Base64.encodeToString((user + ":" + pass).getBytes(), Base64.NO_WRAP);
String authHeader = "Basic " + base;
new NetworkWork().execute(builder.build().toString(), authHeader);
//(...)
//Then we build the actual AsyncTask
class NetworkWork extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... url) {
if (url == null || url[0] == null) return ERROR;
OkHttpClient client = new OkHttpClient();
Request.Builder builder = new Request.Builder().url(url[0]);
//here we add the Basic Authentication header
if (url.length > 1) builder.addHeader("Authorization", url[1]);
try (Response response = client.newCall(builder.build()).execute()) {
if(!response.isSuccessful()) return ERROR
return response.body().string();
} catch (IOException e) {
e.printStackTrace();
return ERROR;
}
}
@Override
protected void onPostExecute(String s) {
if (s.equals(ERROR)) {
Toast.makeText(MainActivity.this, "Cannot fetch data from GitHub!", Toast.LENGTH_SHORT).show();
} else decodeJson(s);
}
}
//Finally we decode the JSON (see above)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment