【问题标题】:Getting file from URL - error从 URL 获取文件 - 错误
【发布时间】:2015-08-17 10:07:38
【问题描述】:

感谢这个问题(link),我知道如何从互联网上下载文件。但是,我得到的不是 txt 文件中的普通文本,而是 html 响应。有谁知道我做错了什么?

这是我的代码:

                    // Install Authenticator
                MyAuthenticator.setPasswordAuthentication("Username", "Password");
                Authenticator.setDefault (new MyAuthenticator(Main.getPropertyPath()));

                URL website = new URL("http://.../5-Anhang.txt?revision=1260");
                ReadableByteChannel rbc = Channels.newChannel(website.openStream());
                FileOutputStream fos = new FileOutputStream("information.txt");
                fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);

已编辑

回复:

<html>
<body onLoad='document.forms["login"].submit();'>
<form id='login' method='POST' action='/polarion/j_security_check'>
<input type='hidden' name='j_username' value='null'/>
<input type='hidden' name='j_password' value='null'/>
<noscript>
<input type='submit' value="Login"/>
</noscript>
</form>
</body>
</html>

【问题讨论】:

  • 可以这样试试吗? URL url = new URL("yourserver.com:80/filename"); // 读取文本 BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = in.readLine()) != null ) { System.out.println(line);// 将此行添加到文件输出流中 } in.close();

标签: java url httpconnection polarion


【解决方案1】:

由于评论不可读,请发布答案。

import java.io.*;
import java.net.*;

public class App {
    public static void main(String[] args) throws Exception{

      URL url = new URL("http://localhost:8080/js/txt1.txt");
        // read text
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
    String line;
        while ((line = in.readLine()) != null) {
        System.out.println(line);
    }
    in.close();
    }
}

以下代码用于读取以下格式的文本文件

Novak Djokovic
Andy Murray
Roger Federer
Nishokiri

输出

诺瓦克·德约科维奇

安迪·穆雷

罗杰·费德勒

锦切

【讨论】:

  • 使用此代码,我得到与我相同的输出:/
  • 我根据修改后的答案在 URL 中的 txt1.txt 中添加了 revision=1260 并能够获取内容。你能提供我你的输出吗?
  • 我已将其添加到我的问题中,遗憾的是,由于我的声誉,我无法将您的回答标记为有用:(
  • 5-Anhang.txt的实际内容是什么?和你在输出中打印的一样吗?
  • 如果您从 URL 中删除“?revision=1260”,您会收到“Hello”吗?
【解决方案2】:

看起来我可能会在网页上搜索“revision=1260”类并返回它

【讨论】:

  • 这应该是评论,而不是答案。
  • 确实如此,但是我还不能放置 cmets,请查看我的代表分数 :)。所以我只是想帮助他
  • 如果您将 cmets 作为答案发布并且他们被否决,那么您的声誉将不会提高...
  • 但是当我在浏览器中输入网址时,会弹出文件下载窗口,我可以下载或打开文件
  • @prosk 当您输入没有“?revision=1260”的网址时,您的浏览器会做什么?
猜你喜欢
  • 2012-07-15
  • 2010-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-21
相关资源
最近更新 更多