2

URL からの zip ファイルのダウンロードに問題があります。Firefox では問題なく動作しますが、私のアプリでは 404 になります。

これが私のコードです

URL url = new URL(reportInfo.getURI().toString());
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();

// Check for errors
int responseCode = con.getResponseCode();
InputStream inputStream;
if (responseCode == HttpURLConnection.HTTP_OK) {
    inputStream = con.getInputStream();
} else {
    inputStream = con.getErrorStream();
}

OutputStream output = new FileOutputStream("test.zip");

// Process the response
BufferedReader reader;
String line = null;
reader = new BufferedReader(new InputStreamReader(inputStream));
while ((line = reader.readLine()) != null) {
    output.write(line.getBytes());
}

output.close();
inputStream.close();

何か案が ?

4

2 に答える 2

4

Java 7 で URL をファイルに保存する最も簡単な方法は次のとおりです。

try (InputStream stream = con.getInputStream()) {
    Files.copy(stream, Paths.get("test.zip"));
}
于 2013-06-05T17:17:22.280 に答える
1

なぜ 404 を取得しているのかについては、わかりにくいです。の値を確認する必要があります。urlこれは greedybuddha が言うように、経由で取得する必要がありますURI.getURL()。ただし、サーバーがユーザー エージェント チェックなどを使用して、リソースを提供するかどうかを判断している可能性もあります。cURLのようなものを使ってプログラムでフェッチすることもできますが、自分でコードを書く必要はありません。

ただし、別の問題が迫っています。zipファイルです。それがバイナリデータです。しかし、テキストコンテンツInputStreamReader用に設計された を使用しています。そうしないでください。バイナリ データには絶対に使用しないでください。を使用するだけです:ReaderInputStream

byte[] buffer = new byte[8 * 1024]; // Or whatever
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) > 0) {
    output.write(buffer, 0, bytesRead);
}

finallyストリームをブロックで閉じるか、Java 7 を使用している場合は try-with-resources ステートメントを使用する必要があることに注意してください。

于 2013-06-05T14:54:49.600 に答える