【问题标题】:How to transfer a file from REST php server to a Java client如何将文件从 REST php 服务器传输到 Java 客户端
【发布时间】:2013-10-21 21:30:08
【问题描述】:

我一直在浏览这个网站,寻找一个示例或“隧道尽头的曙光”,以了解如何编写代码,让我可以将文件从 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 与服务器上有什么?文件大小匹配?不?在文本/十六进制编辑器中打开下载的版本,看看有什么不同?
  • 我猜你应该读写byte[]s 而不是Strings。
  • 是您只在 PHP 中编码,还是您实际上是在发送标头,例如通常会这样做。在此处查看第一个示例以获取更多信息。 php.net/manual/en/function.readfile.php
  • 是的,我从 PHP 发送了正确的标题。问题出在 JAVA 客户端上,尝试使用 Writter 对象编写下载而不是使用输入/输出流。我现在正确地测试、下载和播放了音频文件。谢谢大家。

标签: java php rest


【解决方案1】:

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

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

尝试以下方法:

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
}

【讨论】:

  • 答案是: URL url=new URL("xyz.com/id"); HttpURLConnection connection=(HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); IntpuStream in = connection. getInputStream(); FileOutputStream out =new FileOutputStream("file.mp3"); copy(in, out, 1024); out.close(); public static void copy(InputStream input, OutputStream output, int bufferSize) throws IOException { byte [] buf = new byte[bufferSize]; int n = input.read(buf); while (n >= 0) { output.write(buf, 0, n); n = input.read(buf); } 输出.flush(); }
  • 你在回答中说的很酷,而且很有效。谢谢!
  • 此链接指向同一主题:stackoverflow.com/questions/18445593/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-01
  • 2019-07-12
相关资源
最近更新 更多