如何将文件从 REST php 服务器传输到 Java 客户端


How to transfer a file from REST php server to a Java client

我一直在这个网站上冲浪,寻找一个关于如何编写代码的例子或"隧道尽头的光",让我将文件从PHP的REST服务器下载到JAVA的客户端。

客户端将使用文件的ID发出GET请求,然后PHP REST代码应该响应该文件,JAVA接收该文件并将其存储在硬盘驱动器中。

知道吗...?我试图像这样做 PHP Rest 服务器...:

$file = 'path_to_file/file.mp3';
$content = readfile($file);

而这个$content变量,作为响应发送...

客户端...我写的是:

try {
    URL url = new URL("url/to/rest/server");
    HttpURLConnection conn (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setRequestProperty("Accept", "Content-Disposition: filename'"music.mp3'"");
    if(conn.getResponseCode() != 200) {
        throw new RuntimeException("Failed : HTTP error code: " + conn.getResponseCode());
    }
    BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
    try {
        String output;
        File newFile = newFile("/some/path/file.mp3");
        fileWriter fw = new FileWriter(newFile);
        while ((output = br.readLine()) != null) {
            fw.write(output);
        }
        fw.close();
    } catch (IOException iox) {
        //do
    }
} catch (MalformedURLException e) {
    //do
}

我的示例的问题在于,当我在客户端上收到文件时,文件已损坏或其他原因...在我的MP3文件中,客户端上的任何音乐播放器都说该文件已损坏或无法正常工作。

感谢您的任何帮助。

在处理二进制数据(MP3文件)时,您应该使用InputStream和OutputStream,而不是Readers/Writers。此外,BufferedReader.readLine() 也会从输出中删除任何"换行符"。

因为您使用的是读取器/写入器,所以二进制数据正在转换为字符串,我确信发生了很多损坏。

请尝试以下操作:

InputStream is = conn.getInputStream();
byte[] buffer = new byte[10240]; // 10K is a 'reasonable' amount
try {
    File newFile = newFile("/some/path/file.mp3");
    FileOutputStream fos = new FileOutputStream(newFile);
    int len = 0;
    while ((len = is.read(buffer)) >= 0) {
        fos.write(buffer, 0, len);
    }
    fos.close();
} catch (IOException iox) {
    //do
}