Skip to content

Commit

Permalink
Refactored Http requests
Browse files Browse the repository at this point in the history
  • Loading branch information
frankenbeanies committed Sep 14, 2016
1 parent 8286a42 commit c80227a
Showing 1 changed file with 14 additions and 34 deletions.
48 changes: 14 additions & 34 deletions com/samuelbostick/jfood2fork/Food2Fork.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,40 +15,24 @@ public Food2Fork(String apiKey){
_apiKey = apiKey;
}

public Recipe getRecipe(int id) throws Exception{
HttpURLConnection urlConnection = null;
String json = "";
try{
URL url = new URL("http://food2fork.com/api/get?key=" + _apiKey + "&rId=" + id);
urlConnection = (HttpURLConnection) url.openConnection();
InputStreamReader reader = new InputStreamReader(url.openStream());

int d = reader.read();
while(d != -1){
json += (char)d;
d = reader.read();
}
}catch(MalformedURLException e){
throw new Exception("Malformed apiKey or recipeID");

}finally{
if(urlConnection != null){
urlConnection.disconnect();
}
}

System.out.println(json);

public Recipe getRecipe(int id) throws IOException{
String json = getJsonFromUrl("http://food2fork.com/api/get?key=" + _apiKey + "&rId=" + id);
Genson genson = new GensonBuilder().useRuntimeType(true).create();
return genson.deserialize(json, RecipeContainer.class).recipe;
}

public SearchResult search(String query, char sort, int page) throws Exception{
public SearchResult search(String query, char sort, int page) throws MalformedURLException, IOException{
String json = getJsonFromUrl("http://food2fork.com/api/search?key=" + _apiKey
+ "&q=" + query + "&sort=" + sort + "&page=" + page);
Genson genson = new GensonBuilder().useRuntimeType(true).create();
return genson.deserialize(json, SearchResult.class);
}

private String getJsonFromUrl(String s) throws IOException{
HttpURLConnection urlConnection = null;
String json = "";
try{
URL url = new URL("http://food2fork.com/api/search?key=" + _apiKey
+ "&q=" + query + "&sort=" + sort + "&page=" + page);
URL url = new URL(s);
urlConnection = (HttpURLConnection) url.openConnection();
InputStreamReader reader = new InputStreamReader(url.openStream());

Expand All @@ -57,18 +41,14 @@ public SearchResult search(String query, char sort, int page) throws Exception{
json += (char)d;
d = reader.read();
}
}catch(MalformedURLException e){
throw new Exception("Malformed parameter");

}catch(IOException e){
throw new IOException("There was an error reading from the url. Check your parameters, and that the endpoint is online.");
}finally{
if(urlConnection != null){
urlConnection.disconnect();
}
}

System.out.println(json);

Genson genson = new GensonBuilder().useRuntimeType(true).create();
return genson.deserialize(json, SearchResult.class);
return json;
}
}

0 comments on commit c80227a

Please sign in to comment.