首页 > 解决方案 > Java - 从 URL 获取页面内容

问题描述

我在这里做错了什么?请记住,我通常使用 C# 而不是 java 编写代码。我现在需要将我的 c# 转换为 java。

Java代码:

public class HelloWorld{

     public static void main(String []args)
     {
         System.out.println("Hello World");
         boolean output;
         try
         {
            URL url = new URL("http://stackoverflow.com/questions/6159118/using-java-to-pull-data-from-a-webpage");
            URLConnection con = url.openConnection();
            InputStream is =con.getInputStream();
            output = true;
         }
         catch(Exception e)
         {
             output = false;
         }
         System.out.println("Result: " + Boolean.toString(output));
     }
}

C#代码是:

using System.Net;


bool output;
try
{
  WebClient wc = new System.Net.WebClient();
  string webData = wc.DownloadString("URL");
  output = true;
}
catch
{
  output = false;
}
Console.WriteLine("Result: " + output.ToString());

我在Java代码中做错了什么?

我收到的错误是:

$javac HelloWorld.java
HelloWorld.java:9: error: cannot find symbol
            URL url = new URL("http://stackoverflow.com/questions/6159118/using-java-to-pull-data-from-a-webpage");
            ^
  symbol:   class URL
  location: class HelloWorld
HelloWorld.java:9: error: cannot find symbol
            URL url = new URL("http://stackoverflow.com/questions/6159118/using-java-to-pull-data-from-a-webpage");
                          ^
  symbol:   class URL
  location: class HelloWorld
HelloWorld.java:10: error: cannot find symbol
            URLConnection con = url.openConnection();
            ^
  symbol:   class URLConnection
  location: class HelloWorld
HelloWorld.java:11: error: cannot find symbol
            InputStream is =con.getInputStream();
            ^
  symbol:   class InputStream
  location: class HelloWorld
4 errors

在本站编译时https://www.tutorialspoint.com/compile_java_online.php

标签: javaurl

解决方案


你的 C# 代码的第一行是Using System.Net;Java,你的import类。在这里你还没有导入URLorURLConnectionInputStream。基本上,添加到您的 Java

import java.net.URL;
import java.net.URLConnection;
import java.io.InputStream;

推荐阅读