java - 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
解决方案
你的 C# 代码的第一行是Using System.Net;
Java,你的import
类。在这里你还没有导入URL
orURLConnection
或InputStream
。基本上,添加到您的 Java
import java.net.URL;
import java.net.URLConnection;
import java.io.InputStream;
推荐阅读
- c++ - 将 UDP 包发送到 Lifx 和 recvfrom
- tensorflow - 将输出张量连接到张量流中的占位符
- php - 如何使用 Guzzle 进行这项工作
- c# - 当实体框架中的模型更改时删除并创建受影响的表
- python - Python Beautiful Soup“隐藏”表
- python - Python Pandas Pivot 图像数据表
- neo4j - gremlin 克隆一个节点及其边缘
- python-3.x - 如何更改python电子邮件中的字体
- javascript - 更改作用域变量 AngularJS 的值
- java - Json Serialize data with different property name