0

我从两天开始就一直坚持这个过程,在发布之前我搜索了很多主题,看起来这是一个非常简单的问题。但我没有得到问题。

场景是基本的:我想通过 http 连接从远程计算机解析 XML:

  import java.io.*;
  import java.net.HttpURLConnection;
  import java.net.URL;
  try {
       URL url = new URL("http://host:port/file.xml");
       HttpURLConnection connection = (HttpURLConnection) url.openConnection();
       connection.setRequestMethod("GET");
       connection.setRequestProperty("Accept","application/xml");
       InputStream is = connection.getInputStream();
       BufferedReader br = new BufferedReader(new InputStreamReader(is));
       PrintWriter pw = new PrintWriter("localfile_pw.xml");
       FileOutputStream fos = new FileOutputStream("localfile_os.xml");

然后我尝试了三种不同的方式来读取 XML

读取字节流

   byte[] buffer = new byte[4 * 1024];
   int byteRead;
   while((byteRead= is.read(buffer)) != -1){
                fos.write(buffer, 0, byteRead);
    }

每个字符读取字符

   char c;
   while((c = (char)br.read()) != -1){
          pw.print(c);
          System.out.print(c);
    }

每行读取行

    String line = null; 
    while((line = br.readLine()) != null){
                pw.println(line);
                System.out.println(line);
    }

在所有情况下,我的 xml 读取在相同的字节数之后停止在同一点。并且没有阅读并且没有给出任何例外就被卡住了。

提前致谢。

4

2 回答 2

0

这个怎么样(参见Apache 的IOUtils):

URL url = new URL("http://host:port/file.xml");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept","application/xml");
InputStream is = connection.getInputStream();
FileOutputStream fos = new FileOutputStream("localfile_os.xml");
IOUtils.copy(is, fos);
is.close();
fos.close();
于 2012-08-01T10:07:21.220 回答
0

默认情况下,该类支持持久 HTTP 连接。如果在响应时知道响应的大小,则在发送您的数据后,服务器将等待另一个请求。有两种处理方法:

  1. 阅读内容长度:

    InputStream is = connection.getInputStream();
    String contLen = connection.getHeaderField("Content-length");
    int numBytes = Integer.parse(contLen);
    

    numBytes从输入流中读取字节。注意:contLen可能为空,在这种情况下,您应该阅读直到 EOF。

  2. 禁用连接保持活动:

    connection.setRequestProperty("Connection","close");
    InputStream is = connection.getInputStream();
    

    发送完最后一个字节的数据后,服务器将关闭连接。

于 2012-08-01T18:25:26.477 回答