download URL and return String - Java Network

Java examples for Network:URL Download

Description

download URL and return String

Demo Code


//package com.java2s;
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 {

    public static String download(URL url) throws IOException {
        String data = "";
        InputStream is = null;//from  w ww .  jav  a 2  s  .com
        HttpURLConnection connection = null;
        try {
            connection = (HttpURLConnection) url.openConnection();
            is = connection.getInputStream();
            BufferedReader br = new BufferedReader(
                    new InputStreamReader(is));

            StringBuffer sb = new StringBuffer();
            String line = "";
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            data = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null)
                is.close();
            if (url != null)
                connection.disconnect();
        }
        return data;
    }
}

Related Tutorials