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を読み取る3つの異なる方法を試しました

バイトストリームの読み取り

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

1 文字あたりの読み取り文字数

   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接続をサポートしています。応答時に応答のサイズがわかっている場合、データを送信した後、サーバーは別の要求を待ちます。これを処理する2つの方法があります:

  1. コンテンツの長さを読む:

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

    numBytes入力ストリームからバイトを読み取ります。注:contLennullの可能性があります。この場合、EOFまで読む必要があります。

  2. 接続を無効にして存続させる:

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

    データの最後のバイトを送信した後、サーバーは接続を閉じます。

于 2012-08-01T18:25:26.477 に答える