Load content from URL to string : URLConnection « Network Protocol « Java






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

1.Demonstrate URLConnection.
2.Call a servlet from a Java command line application
3.A CGI POST Example
4.Http authentication header
5.URLConnection.setRequestProperty
6.File size from URL
7.Sending a POST Request Using a URL
8.Check if a file was modified on the server
9.Getting Text from a URL
10.Getting an Image from a URL
11.Sending a POST Request with Parameters From a Java Class
12.Downloading a web page using URL and URLConnection classes
13.Get response header from HTTP request
14.Read / download webpage content
15.Read a GIF or CLASS from an URL save it locally
16.Zip URLConnection
17.Zip URLStream Handler
18.Http Parser
19.Http Constants
20.Get URLConnection Expiration
21.Locating files by path or URL
22.Download from URL
23.This program demonstrates how to use the URLConnection class for a POST request.
24.Connects to an URL and displays the response header data and the first 10 lines of the requested data.Connects to an URL and displays the response header data and the first 10 lines of the requested data.