簡體   English   中英

Http請求進行遠程XML解析

[英]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連接。 如果在響應時知道響應的大小,則在發送數據后,服務器將等待另一個請求。 有兩種處理方法:

  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(); 

    發送完最后一個數據字節后,服務器將關閉連接。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM