发送zip文件作为Jersey响应并通过cURL下载



我有一个Jersey服务,它返回一个zip文件作为响应。我使用cURL调用这个服务。我得到一个文件响应,但zip文件是不可读的。我注意到原始文件约为20MB,但我得到的文件大小仅为3.2KB

我正在尝试以下代码:

球衣:

 @GET
 @Path("/get-zip")
 @Produces("application/zip")
 @Consumes(MediaType.APPLICATION_JSON)
 public Response getZip() throws IOException{
   File fileObj = new File('myfile.zip');
   return Response.ok((Object)fileObj)
                .header("Content-Disposition", "attachment; filename="" + fileObj.getName() + """)
                .build();
    }

旋度代码:

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HEADER, 1);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1);
    $file = curl_exec($curl);
    $file_array = explode("nr", $file, 2);
    $header_array = explode("n", $file_array[0]);
    foreach($header_array as $header_value) {
      $header_pieces = explode(':', $header_value);
      if(count($header_pieces) == 2) {
        $headers[$header_pieces[0]] = trim($header_pieces[1]);
      }
    }
    header('Content-type: ' . $headers['Content-Type']);
    header('Content-Disposition: ' . $headers['Content-Disposition']);
    echo $file_array[1];

我错过了什么?

    MediaStreamer streamer = new MediaStreamer(fileObj.getInputStream());
    return Response.ok()
            .header(HttpHeaders.CONTENT_LENGTH, fileObj.getContentLength())
            .header(HttpHeaders.CONTENT_DISPOSITION, fileObj.getContentDisposition())
            .entity(streamer)
            .type(fileObj.getContentType())
            .build();

MediaStreamer看起来像这样

import com.google.common.io.ByteStreams;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.StreamingOutput;
import java.io.*;
public class MediaStreamer implements StreamingOutput {
    private InputStream is;
    public MediaStreamer(InputStream is) {
        this.is = is;
    }
    @Override
    public void write(OutputStream os) throws IOException, WebApplicationException {
        Writer writer = new BufferedWriter(new OutputStreamWriter(os));
        ByteStreams.copy(is, os);
        writer.flush();
    }
}

最新更新