开发者

Java URL hangs and never reads in Website

开发者 https://www.devze.com 2023-04-05 11:08 出处:网络
I am trying to read in a website and save it to a string.I\'m using this code below which works perfectly fine in Eclipse.But when I try to run the program via the command line in Windows like \"java

I am trying to read in a website and save it to a string. I'm using this code below which works perfectly fine in Eclipse. But when I try to run the program via the command line in Windows like "java MyProgram", the program starts and just hangs and never reads in the URL. Anyone know why this would be happening?

URL link = new URL("http://www.yahoo.com");

            BufferedReader in = new BufferedReader(new InputStreamReader(link.openStream()));
            //InputStream in = link.openStream();
            String inputLine = "";
            int count = 0;
            while ((inputLine = in.readLine()) != null)
            开发者_Go百科{
                site = site + "\n" + inputLine;
            }
            in.close();

...


It could be because you are behind a proxy, and Eclipse is automatically adding settings in to configure this.

If you are behind a proxy, when running from the command prompt, try setting the java.net.useSystemProxies property. You can also manually configure proxy settings with a few network properties found here (http.proxyHost, http.proxyPort).


I encountered such a problem and found a solution. Here my working code:

// Create a URL for the desired page
URL url = new URL("your url");
// Get connection
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5000); // 5 seconds connectTimeout
connection.setReadTimeout(5000 ); // 5 seconds socketTimeout

// Connect
connection.connect(); // Without this line, method readLine() stucks!!!
// because it reads incorrect data, possibly from another memory area

InputStreamReader isr = new InputStreamReader(url.openStream(),"UTF-8");
BufferedReader in = new BufferedReader(isr);
String str;

while (true) {
   str = in.readLine();
   if(str==null){break;}
   listItems.add(str);
}

// Closing all
in.close();
isr.close();
connection.disconnect();


If that's all your code is doing, there's no reason it shoudln't work from the command line. I suspect you've cut out what's broken. For example:

public static void main(String[] args) throws Exception {
    String site = "";
    URL link = new URL("http://www.yahoo.com");
    BufferedReader in = new BufferedReader(new InputStreamReader(link.openStream()));
    //InputStream in = link.openStream();
    String inputLine = "";
    int count = 0;
    while ((inputLine = in.readLine()) != null) {
        site = site + "\n" + inputLine;
    }
    in.close();
    System.out.println(site);
}

works fine. Another possibility would be if you're running it in Eclipse and from the command line on two different computers, and the latter can't reach http://www.yahoo.com.

0

精彩评论

暂无评论...
验证码 换一张
取 消