Skip to content

Instantly share code, notes, and snippets.

@csabafarkas
Last active September 7, 2018 14:10
Show Gist options
  • Save csabafarkas/ecb45840c975ebe91868edf526c1a370 to your computer and use it in GitHub Desktop.
Save csabafarkas/ecb45840c975ebe91868edf526c1a370 to your computer and use it in GitHub Desktop.
Example NetworkUtils wit URL builder
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