无法从url读取js文件 - 收到空的html文件

时间:2018-02-12 12:12:10

标签: javascript java url

我想从url https://www.hellobank.fr/rsc/contrib/script/hb2/js/app/pages/video-bienvenue.js

中读取js文件作为字符串

我的代码是:

StringBuilder sb = new StringBuilder();
URL url = new URL(jsUrl);
URLConnection cnt = url.openConnection();
InputStream stream = new URL(jsUrl).openStream();
if ("gzip".equalsIgnoreCase(cnt.getHeaderField("Content-Encoding"))) {
  stream = new GZIPInputStream(stream);
}
// read text returned by server
BufferedReader in = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
String line;
while ((line = in .readLine()) != null) {
  sb.append(line).append("\n");
} in .close();

而不是js的真实内容我收到了空的html文件:

<html>
<body>
<script type="text/javascript">
   window.location = "/fr/systeme/maintenance?&ID=12646317151369496393&eq=LSM2TDBW";
</script>
</body>
</html>

有人可以帮我理解js链接有什么问题以及如何正确阅读?

1 个答案:

答案 0 :(得分:1)

您应该发送GET请求,就像在浏览器中一样。 您可以阅读有关如何执行此操作here

您的代码与示例中的代码几乎相同:

    URL obj = new URL("https://www.hellobank.fr/rsc/contrib/script/hb2/js/app/pages/video-bienvenue.js");
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod("GET");
    con.setRequestProperty("User-Agent", "Mozilla/5.0");
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();
    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    System.out.println(response.toString()); //here is the content of the file you need

或更接近您的代码,它将是这样的:

    String jsUrl = "https://www.hellobank.fr/rsc/contrib/script/hb2/js/app/pages/video-bienvenue.js";
    URL obj = new URL(jsUrl);
    HttpURLConnection cnt = (HttpURLConnection) obj.openConnection();
    cnt.setRequestMethod("GET");
    cnt.setRequestProperty("User-Agent", "Mozilla/5.0");
    InputStream stream = cnt.getInputStream();
    if ("gzip".equalsIgnoreCase(cnt.getHeaderField("Content-Encoding"))) {
          stream = new GZIPInputStream(stream);
    }
    BufferedReader in = new BufferedReader(new InputStreamReader(stream));
    String inputLine;
    StringBuffer response = new StringBuffer();
    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
    System.out.println(response.toString()); //here is the content of the file you need