无法实现下载

xzzgz 2008-04-19 12:41:12
本人在下载一段代码,功能是下载网页内容: http://bill.finance.sina.com.cn/bill/trade_item_download.php?stock_code=sz000877 ,下载的文件报无法找到网页,手工没有问题.代码如下,请问怎么解决:
public static void main(String[] args) {
try {
// Check the arguments
if ((args.length != 1) && (args.length != 2))
throw new IllegalArgumentException("Wrong number of args");

// Get an output stream to write the URL contents to
OutputStream to_file;
if (args.length == 2) to_file = new FileOutputStream(args[1]);
else to_file = System.out;

// Now use the URL class to parse the user-specified URL into
// its various parts.
URL url = new URL(args[0]);
String protocol = url.getProtocol();
if (!protocol.equals("http")) // Check that we support the protocol
throw new IllegalArgumentException("Must use 'http:' protocol");
String host = url.getHost();
int port = url.getPort();
if (port == -1) port = 80; // if no port, use the default HTTP port
String filename = url.getFile();


// Open a network socket connection to the specified host and port
Socket socket = new Socket(host, port);

// Get input and output streams for the socket
InputStream from_server = socket.getInputStream();
PrintWriter to_server = new PrintWriter(socket.getOutputStream());

// Send the HTTP GET command to the Web server, specifying the file
// This uses an old and very simple version of the HTTP protocol
to_server.print("GET " + filename + "\n\n");
to_server.flush(); // Send it right now!

// Now read the server's response, and write it to the file
byte[] buffer = new byte[4096];
int bytes_read;
while((bytes_read = from_server.read(buffer)) != -1)
to_file.write(buffer, 0, bytes_read);

// When the server closes the connection, we close our stuff
socket.close();
to_file.close();
}
catch (Exception e) { // Report any errors that arise
System.err.println(e);
System.err.println("Usage: java HttpClient <URL> [<filename>]");
}
}
...全文
62 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
shadowlin 2008-04-19
  • 打赏
  • 举报
回复
你这个看了下没看太懂...
你看看这个你能用不?

http://www.examda.com/Java/jichu/20061127/101321301-2.html

62,623

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧