2014-07-12 2 views
6

저지/JAX-RS 구현에 익숙하지 않습니다.저지 클라이언트가 파일을 다운로드하고 저장합니다.

Client client = Client.create(); 
WebResource wr = client.resource("http://localhost:7070/upload-0.0.1-SNAPSHOT/rest/files/download"); 
Builder wb=wr.accept("application/json,application/pdf,text/plain,image/jpeg,application/xml,application/vnd.ms-excel"); 
ClientResponse clientResponse= wr.get(ClientResponse.class); 
System.out.println(clientResponse.getStatus()); 
File res= clientResponse.getEntity(File.class); 
File downloadfile = new File("C://Data/test/downloaded/testnew.pdf"); 
res.renameTo(downloadfile); 
FileWriter fr = new FileWriter(res); 
fr.flush(); 

내 서버 측 코드는 다음과 같습니다 : 파일을 다운로드 내 저지 클라이언트 코드를 검색

내 클라이언트 코드 내가 200 OK로 응답을 받고 있어요,하지만 난 저장할 수 없습니다 오전에
@Path("/download") 
    @GET 
    @Produces({"application/pdf","text/plain","image/jpeg","application/xml","application/vnd.ms-excel"}) 
    public Response getFile() 
    { 

     File download = new File("C://Data/Test/downloaded/empty.pdf"); 
     ResponseBuilder response = Response.ok((Object)download); 
     response.header("Content-Disposition", "attachment; filename=empty.pdf"); 
     return response.build(); 
    } 

하드 디스크에 내 파일 아래 라인에서 파일을 저장해야하는 경로와 위치를 언급합니다. 여기에 무슨 일이 일어나고 있는지 확실하지 않은 경우 도움을 얻을 수 있습니다. 미리 감사드립니다 !!

File downloadfile = new File("C://Data/test/downloaded/testnew.pdf"); 

답변

4

저지 당신이 여기 가지고있는 것처럼 당신은 단순히 파일로 응답하자 경우 나도 몰라 :

File download = new File("C://Data/Test/downloaded/empty.pdf"); 
ResponseBuilder response = Response.ok((Object)download); 

당신은 확실히 서버에서 파일을 보낼 StreamingOutput 응답을 사용할 수 있습니다, 이 같은 :

StreamingOutput stream = new StreamingOutput() { 
    @Override 
    public void write(OutputStream os) throws IOException, 
    WebApplicationException { 
     Writer writer = new BufferedWriter(new OutputStreamWriter(os)); 

     //@TODO read the file here and write to the writer 

     writer.flush(); 
    } 
}; 

return Response.ok(stream).build(); 

하고 클라이언트가 스트림을 읽고 파일에 넣어 기대 :

를 0
InputStream in = response.getEntityInputStream(); 
if (in != null) { 
    File f = new File("C://Data/test/downloaded/testnew.pdf"); 

    //@TODO copy the in stream to the file f 

    System.out.println("Result size:" + f.length() + " written to " + f.getPath()); 
} 
+0

@GET 대신 @POST로 할 수 있습니까? – spr

+0

그것은 확실히입니다. 대체로 그들은 상호 교환 가능합니다. 나는 몸을 보호 할 수 있고 매개 변수가 보이지 않기 때문에 보통 게시물을 선호한다. –

2

해결책을 찾고있는 사람들을 위해 jaxrs 응답을 파일에 저장하는 방법에 대한 전체 코드는 다음과 같습니다.

public void downloadClient(){ 
    Client client = ClientBuilder.newClient(); 
    WebTarget target = client.target("http://localhost:7070/upload-0.0.1-SNAPSHOT/rest/files/download"); 

    Response resp = target 
     .request("application/pdf,image/jpeg,application/xml,application/vnd.ms-excel") 
     .get(); 

    if(resp.getStatus() == Response.Status.OK.getStatusCode()) 
    { 
     InputStream is = resp.readEntity(InputStream.class); 
     fetchFeed(is); 
     //fetchFeedAnotherWay(is) //use for Java 7 
     IOUtils.closeQuietly(is); 
     System.out.println("the file details after call:"+downloadfile.getAbsolutePath()+", size is "+downloadfile.length()); 
    } 
    else{ 
     throw new WebApplicationException("Http Call failed. response code is"+resp.getStatus()+". Error reported is"+resp.getStatusInfo()); 
    } 
} 
/** 
* Store contents of file from response to local disk using java 7 
* java.nio.file.Files 
*/ 
private void fetchFeed(InputStream is){ 
    File downloadfile = new File("C://Data/test/downloaded/testnew.pdf"); 
    byte[] byteArray = IOUtils.toByteArray(is); 
    FileOutputStream fos = new FileOutputStream(downloadfile); 
    fos.write(byteArray); 
    fos.flush(); 
    fos.close(); 
} 

/** 
* Alternate way to Store contents of file from response to local disk using 
* java 7, java.nio.file.Files 
*/ 
private void fetchFeedAnotherWay(InputStream is){ 
    File downloadfile = new File("C://Data/test/downloaded/testnew.pdf"); 
    Files.copy(is, downloadfile.toPath(), StandardCopyOption.REPLACE_EXISTING); 
} 
2

아래의 샘플 코드는 도움이 될 수 있습니다.

https://stackoverflow.com/a/32253028/15789

은 JAX의 RS 나머지 서비스, 테스트 클라이언트입니다. 파일에서 바이트를 읽고 REST 서비스에 바이트를 업로드합니다. REST 서비스는 바이트를 압축하여 바이트로 클라이언트에 다시 보냅니다. 클라이언트는 바이트를 읽고 zip 파일을 저장합니다. 다른 스레드에 대한 응답으로 게시했습니다.

0

다음은 Files.copy()를 사용하여 수행하는 또 다른 방법입니다.

private long downloadReport(String url){ 

      long bytesCopied = 0; 
      Path out = Paths.get(this.fileInfo.getLocalPath()); 

      try { 

       WebTarget webTarget = restClient.getClient().target(url); 
       Invocation.Builder invocationBuilder = webTarget.request(MediaType.TEXT_PLAIN_TYPE); 

       Response response = invocationBuilder.get(); 

       if (response.getStatus() != 200) { 
        System.out.println("HTTP status " response.getStatus()); 
        return bytesCopied; 
       } 

       InputStream in = response.readEntity(InputStream.class); 
       bytesCopied = Files.copy(in, out, REPLACE_EXISTING); 

       in.close(); 

      } catch(IOException e){ 
       System.out.println(e.getMessage()); 
      } 

      return bytesCopied; 
    } 
관련 문제