有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java无法通过URL连接从站点加载内容

我试图从url连接加载站点http://www.povarenok.ru/,但内容为空。我尝试了其他网站-所有作品。请帮忙,这个网站有什么问题吗

    URL url;

    try {

        url = new URL("http://www.povarenok.ru/");
        URLConnection conn = url.openConnection();

        BufferedReader br = new BufferedReader(new InputStreamReader(
                conn.getInputStream()));

        String inputLine;

        String fileName = "c:\\test.html";
        File file = new File(fileName);

        if (!file.exists()) {
            file.createNewFile();
        }

        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);

        //inputLine is empty!!! All works with other sites
        while ((inputLine = br.readLine()) != null) {
            bw.write(inputLine);
        }

        bw.close();
        br.close();

        System.out.println("Done");

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

共 (1) 个答案

  1. # 1 楼答案

    改为:

     url = new URL("http://www.povarenok.ru");
                                           ^ - no slash here
    

    看起来此网站已将/配置为其他用途

    [编辑]

    再次检查,这个斜杠实际上不是这样,从我看到它在更改urser代理后开始工作(将其放在BufferedReader创建之前):

    ((HttpURLConnection)conn).setRequestProperty("User-Agent", "SO");
    

    关于如何在Windows with Fiddler上调试此类问题的提示:

    您应该首先安装fiddler2——它将允许您查看您的请求。在java应用程序中,在应用程序开始时添加以下行:

        System.setProperty("http.proxyHost", "127.0.0.1");
        System.setProperty("https.proxyHost", "127.0.0.1");
        System.setProperty("http.proxyPort", "8888");
        System.setProperty("https.proxyPort", "8888");
    

    现在,假设您有一个在webbrowser中加载的站点,但没有在java应用中加载。您必须比较请求头并找出差异。因此,您可以在webbrowser中加载页面,然后在应用程序中加载页面,并使用fiddler比较结果