未能获取网页的源代码



我正在尝试从该网站获取HTML页面源内容:"http://207.200.96.231:8008"使用Java。然而,Java的默认库在这方面对我没有帮助。我也尝试过使用本教程,但它也不起作用。我认为问题的出现是因为网站的安全保护。当我运行下面提供的以下代码时,我得到了一个异常:java.io.IOException: Invalid Http response.

有关于如何实现代码的想法吗?或者有什么图书馆可以满足我的需求吗?到目前为止,我已经尝试过JSoupJericho HTML Parser,认为它们会使用不同的方法连接到我提供的网站,但它们也无法工作。

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和垃圾神的帮助下,我设法解决了这个问题。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-vhttp://207.200.96.231:8008*即将连接()到207.200.96.231端口8008(#0)*正在尝试207.200.96.231…已连接*接207.200.96.231(207.200.96.331)端口8008(#0)它似乎需要[Winamp][2]。>获取HTTP://1.1>用户代理:curl/。。。>主持人:207.200.96.231:8008>接受:*/*>结冰200 OKicy-notice1:
此流需要Winamp
icy-notice2:SHOUTcast分布式网络音频服务器/Linux v1.993atdn
冰冷的名字:绝对流畅的爵士乐-SKY.FM-世界上24小时最流畅的爵士乐冰冷的流派:柔和流畅的爵士乐冰冷的网址:http://www.sky.fm/smoothjazz/内容类型:audio/mpeg冰冷的酒吧:1冰冷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);
}

最新更新