Http请求远程XML解析

时间:2012-08-01 10:01:37

标签: java xml xmlhttprequest inputstream

我在这个过程中坚持了两天,在发布之前我已经搜索了很多主题,看起来这是一个如此简单的问题。但我没有遇到问题。

场景是基本的:我想通过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);
    }

每个角色阅读charachter

   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读数在相同的精确的字节数之后停在同一点。并且在没有阅读的情况下卡住而且没有任何例外。

提前致谢。

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分:0)

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

  1. 阅读内容长度:

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

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

  2. 禁用连接保持活动状态:

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

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