Skip to content

Instantly share code, notes, and snippets.

@janishar
Created October 3, 2016 11:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save janishar/0ea95236da4c46a2665731b764cd3844 to your computer and use it in GitHub Desktop.
Save janishar/0ea95236da4c46a2665731b764cd3844 to your computer and use it in GitHub Desktop.
public class ApiHandler{
public static String GIT_REPO_URL = "https://api.github.com/users/mralexgray/repos";
private static final int API_CHANNEL_ID = 1000;
private static ApiHandler apiHandler;
public static void init(){
apiHandler = new ApiHandler();
}
public ApiHandler() {
try {
JPost.getBroadcastCenter().createPrivateChannel(this, API_CHANNEL_ID);
}catch (Exception e){
e.printStackTrace();
}
}
public static void doGitRepoGetApiCall(String url){
try {
JPost.getBroadcastCenter().broadcastAsync(apiHandler, API_CHANNEL_ID, url);
}catch (JPostNotRunningException e){
e.printStackTrace();
}
}
@OnMessage(channelId = API_CHANNEL_ID)
public void processGitRepoGet(String url) {
try {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
Log.d("Debug", "Response Code : " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
Log.d("Debug", "Response : " + response);
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
GitRepo[] gitRepoArray = gson.fromJson(response.toString(), GitRepo[].class);
JPost.getBroadcastCenter().broadcastAsync(new GitRepoMsg(Arrays.asList(gitRepoArray)));
}
}catch (MalformedURLException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}catch (JPostNotRunningException e){
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment