I want to get the information from the website using HttpURLConnection.I wrote this

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class webPractice

public static void main(String[] args)

URL yahoo = new URL("http://www.yahoo.com");
URLConnection yahooConnection = (URLConnection) yahoo.openConnection();
long s=yahooConnection.getDate();

catch (MalformedURLException e)

System.out.println("URL Exception");
// new URL() failed
catch (IOException es)
System.out.println("IO Exception");
// openConnection() failed
catch(Exception ex)



but ,i have an exception

java.lang.ClassCastException: sun.net.www.protocol.http.HttpURLConnection$HttpInputStream cannot be cast to java.lang.String

how can i retrieve data from the website?
If any have the working code pls show me

thank you in advance

Edited 5 Years Ago by peter_budo: Adding code tags to old post

The problem appears to be in (String)yahooConnection.getContent() Check the API doc for this method - it returns an Object, in this case its an HttpInputStream object) and that kind of object cannot be simply cast to a String. (In fact it's not even a public class).
You should probably be using yahooConnection.getInputStream(); which returns an input stream from which you can read the lines that have been obtained from the URL.

import java.net.*;
import java.io.*;
public class WebSiteReader {
  public static void main(String args[]){
       String nextLine;
       URL url = null;
       URLConnection urlConn = null;
       InputStreamReader  inStream = null;
       BufferedReader buff = null;
          // Create the URL obect that points
          // at the default file index.html
          url  = new URL("http://www.yahoo.com" );
          urlConn = url.openConnection();
         inStream = new InputStreamReader( 
           buff= new BufferedReader(inStream);
       // Read and print the lines from index.html
        while (true){
            nextLine =buff.readLine();  
            if (nextLine !=null){
     } catch(MalformedURLException e){
       System.out.println("Please check the URL:" + 
                                           e.toString() );
     } catch(IOException  e1){
      System.out.println("Can't read  from the Internet: "+ 
                                          e1.toString() ); 

Edited 5 Years Ago by peter_budo: Keep It Clear - Please use code tags when posting any code

If you can't be bothered to post your code properly formatted in code tags (as I requested before) and without any indication as to what your question might be... then I can't be bothered to read it.

This article has been dead for over six months. Start a new discussion instead.