Load content from URL to string
/*
* Copyright (C) 2007 Vianney le Clment
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//package fsahoraires.util;
import java.io.*;
import java.net.URL;
import java.nio.charset.Charset;
public class Util {
/**
* Charge une url et renvoie le contenu
*
* @param url
* @return le contenu de l'url ou "" si erreur
*/
public static String loadUrl(URL url) throws IOException {
InputStream stream = null;
try {
stream = url.openStream();
return loadStream(stream);
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
}
}
}
}
/**
* Charge le contenu d'un stream dans un string
*
* @param stream
* @return
* @throws IOException
*/
public static String loadStream(InputStream stream) throws IOException {
Reader reader = new InputStreamReader(stream, Charset.forName("UTF-8"));
char[] buffer = new char[1024];
int count;
StringBuilder str = new StringBuilder();
while ((count = reader.read(buffer)) != -1)
str.append(buffer, 0, count);
return str.toString();
}
}
Related examples in the same category