Skip to content

Instantly share code, notes, and snippets.

@Razeeman
Last active January 30, 2019 12:45
Show Gist options
  • Save Razeeman/8daec6a37a8fe9a75e4de06426f4c050 to your computer and use it in GitHub Desktop.
Save Razeeman/8daec6a37a8fe9a75e4de06426f4c050 to your computer and use it in GitHub Desktop.
Android, Java, Network, Build Url, Build Uri, HttpURLConnection.
/**
* Builds the URL from query string.
*
* @param searchQuery The search string that will be queried for.
* @return The URL to use for the query.
*/
public static URL buildUrl(String searchQuery) {
String baseUrl = "https://api.github.com/search/repositories";
String paramQuery = "q";
Uri builtUri = Uri.parse(baseUrl).buildUpon()
.appendQueryParameter(paramQuery, searchQuery)
.build();
URL url = null;
try {
url = new URL(builtUri.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
return url;
}
/**
* This method returns the entire result from the HTTP response.
*
* @param url The URL to fetch the HTTP response from.
* @return The contents of the HTTP response.
* @throws IOException Related to network and stream reading
*/
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