简体   繁体   中英

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

I've been surfing over this site looking for an example or "light at the end of the tunnel" about how to write a code that let me download a file from a REST server in PHP to a client in JAVA.

The client will make a GET request with an ID of the file, and then the PHP REST code should response with the file, and JAVA receive that file and store it in the Hard Drive.

Any idea...? I tried to do the PHP Rest server like this...:

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

And this $content var, is sent as the response...

The client... I wrote is:

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
}

The problem with my examples is that when I receive the file on the client is kind of corrupted or something!... in my example with an mp3 file, any music player on the client says that file is corrupted or it doesn't work.

Thanks for any help.

When dealing with binary data (MP3 files) you should use InputStream and OutputStream and not Readers/Writers. Additionally, the BufferedReader.readLine() strips any 'newlines' from the output too.

Because you are using Readers/Writers, the binary data is being converted to Strings, and I am sure there's a lot of corruption happening.

Try the following:

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM