Github query URL (using Uri) and get the response data in Android

   /*These utilities will be used to communicate with the network.*/
    public class NetworkUtils {

    final static String GITHUB_BASE_URL =
            "https://api.github.com/search/repositories";

    final static String PARAM_QUERY = "q";

   /**The sort field.Default: results are sorted by best match 
    * if no field is specified.*/    
    final static String PARAM_SORT = "sort";
    final static String sortBy = "stars";

    /**    
     * Builds the URL used to query Github.  
     * @param githubSearchQuery The keyword that will be queried for.     
     * @return The URL to use to query the weather server.    
     */   
    public static URL buildUrl(String githubSearchQuery) {
        // To build the proper Github query URL        
       Uri builtUri = Uri.parse(GITHUB_BASE_URL)
                .buildUpon()
                .appendQueryParameter(PARAM_QUERY,githubSearchQuery)
                .appendQueryParameter(PARAM_SORT,sortBy)
                .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();
        }
    }
}

Bu blogdaki popüler yayınlar

About Android padding, margin, width, height, wrap_content, match_parent, R Class