[英]Http Request for remote XML parsing
我从发布开始就停留了两天,在发布之前,我已经搜索了很多主题,看起来这是一个非常简单的问题。 但是我没有问题。
场景是基本的:我想通过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读取都在相同的精确字节数之后停止在同一点。 并被卡住而没有阅读,也没有给出任何例外。
提前致谢。
怎么样(请参阅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();
该类默认情况下支持持久HTTP连接。 如果在响应时知道响应的大小,则在发送数据后,服务器将等待另一个请求。 有两种处理方法:
阅读内容长度:
InputStream is = connection.getInputStream(); String contLen = connection.getHeaderField("Content-length"); int numBytes = Integer.parse(contLen);
从输入流中读取numBytes
个字节。 注意: contLen
可以为null,在这种情况下,您应该阅读直到EOF。
禁用连接保持活动状态:
connection.setRequestProperty("Connection","close"); InputStream is = connection.getInputStream();
发送完最后一个数据字节后,服务器将关闭连接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.