Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

import java.io.BufferedReader;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import java.net.HttpURLConnection;
import java.net.URL;

public class Main {
    /**
     * This method fetches data from a given url
     *
     * @param strUrl Url from which the data will be fetched
     * @return A String representing the resource obtained in the connection
     * @throws IOException If something went wrong with the connection
     */
    public static String getDataFromUrl(String strUrl) throws IOException {
        InputStream iStream;
        HttpURLConnection urlConnection;
        URL url = new URL(strUrl);

        // Creating an http connection to communicate with url
        urlConnection = (HttpURLConnection) url.openConnection();

        // Connecting to url
        urlConnection.connect();

        // Reading data from url
        iStream = urlConnection.getInputStream();

        BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

        StringBuilder sb = new StringBuilder();

        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        br.close();
        iStream.close();
        urlConnection.disconnect();
        return sb.toString();
    }
}