无法获取网页的源代码
问题描述:
我正在尝试使用Java从此网站获取HTML页面源内容:“http://207.200.96.231:8008”。但是默认的Java库并没有帮助我。我也尝试使用这个tutorial,但它也没有工作。我认为问题是由于网站的安全保护而发生的。当我运行下面提供的以下代码时,我得到一个异常:java.io.IOException: Invalid Http response
。无法获取网页的源代码
有关如何实现代码的任何想法?还是有任何图书馆可以满足我的需求?到目前为止,我已经尝试JSoup
和Jericho
HTML解析器认为他们会使用不同的方法连接到我提供的站点,但他们也失败了。
String urlstr = "http://72.26.204.28:9484/played.html";
try {
URL url = new URL(urlstr);
URLConnection urlc = url.openConnection();
InputStream stream = urlc.getInputStream();
BufferedInputStream buf = new BufferedInputStream(stream);
StringBuilder sb = new StringBuilder();
while (true){
int data = buf.read();
if (data == -1)
break;
else
sb.append((char)data);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
EDIT(问题解决):随着Karai17和trashgod帮助我设法解决这个问题。 Shoutcast页面需要用户代理才能访问其内容。所以我们需要做的是添加以下代码:
urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0");
最新的代码如下所示:
try {
URL url = new URL("http://207.200.96.231:8008/7.html");
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0");
InputStream is = urlConnection.getInputStream();
BufferedInputStream in = new BufferedInputStream(is);
int c;
while ((c = in.read()) != -1) {
System.out.write(c);
}
urlConnection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
答
这流似乎需要Winamp。
$ curl -v http://207.200.96.231:8008 * About to connect() to 207.200.96.231 port 8008 (#0) * Trying 207.200.96.231... connected * Connected to 207.200.96.231 (207.200.96.231) port 8008 (#0) It appears to require [Winamp][2]. > GET/HTTP/1.1 > User-Agent: curl/... > Host: 207.200.96.231:8008 > Accept: */* > ICY 200 OK icy-notice1:
This stream requires Winamp
icy-notice2:SHOUTcast Distributed Network Audio Server/Linux v1.9.93atdn
icy-name:Absolutely Smooth Jazz - SKY.FM - the world's smoothest jazz 24 hours a day icy-genre:Soft Smooth Jazz icy-url:http://www.sky.fm/smoothjazz/ content-type:audio/mpeg icy-pub:1 icy-br:96 ...
附录:可以读取流是这样的:
URL url = new URL("http://207.200.96.231:8008");
URLConnection con = url.openConnection();
InputStream is = con.getInputStream();
BufferedInputStream in = new BufferedInputStream(is);
int c;
while ((c = in.read()) != -1) {
System.out.write(c);
}
对不起,我没有得到它。有没有一种使用java的winamp来获取源代码的方法? – 2012-07-30 02:00:26
我不知道Winamp,但你可以阅读如上所示的流。 – trashgod 2012-07-30 06:11:07
我认为没有太大区别,您提供的代码并未解决我的问题,对不起。 – 2012-07-30 12:19:05