Last active
September 7, 2018 14:10
-
-
Save csabafarkas/ecb45840c975ebe91868edf526c1a370 to your computer and use it in GitHub Desktop.
Example NetworkUtils wit URL builder
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public final class NetworUtils { | |
private static final String BASE_URL = "https://api.example.com"; | |
private static final String FORMAT = "json"; | |
private static final String QUERY_PARAM = "q"; | |
private static final String SOME_OTHER_PARAM = "param"; | |
public static URL buildUrl(String queryParam, String someOtherParam) { | |
Uri constructUri = Uri.parse(BASE_URL).buildUpon() | |
.appendQueryParameter(QUERY_PARAM, queryParam) | |
.appendQueryParameter(SOME_OTHER_PARAM, someOtherParam) | |
.build(); | |
URL url = null; | |
try { | |
url = new URL(constructUri.toString()); | |
} catch (MarlformedURLException e) { | |
e.printStackTrace(); | |
} | |
return url; | |
} | |
public static String getResponseFromHttpUrl(URL url) throws IOException { | |
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); | |
try { | |
InputStream in = urlConnection.getInputStream(); | |
Scanner scanner = new Scanner(in); | |
scanner.useDelimiter("\\A"); | |
boolean hasInput = scanner.hasNext(); | |
if (hasInput) { | |
return scanner.next(); | |
} else { | |
return null; | |
} | |
} finally { | |
urlConnection.disconnect(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment