I am developing a Jersey service that uses the Dropbox API.
I need to publish a shared file for my service (the service will be able to manage all the files, as well as with the Dropbox API).
Client side
So, I implemented a simple client that:
- opens a file
- creates a connection to the url
- sets the correct HTTP method
- creates a
FileInputStream and writes the file to the connection output stream using a byte buffer.
This is the client test code.
public class Client { public static void main(String args[]) throws IOException, InterruptedException { String target = "http://localhost:8080/DCService/REST/professor/upload"; URL putUrl = new URL(target); HttpURLConnection connection = (HttpURLConnection) putUrl.openConnection(); connection.setDoOutput(true); connection.setInstanceFollowRedirects(false); connection.setRequestMethod("POST"); connection.setRequestProperty("content-Type", "application/pdf"); OutputStream os = connection.getOutputStream(); InputStream is = new FileInputStream("welcome.pdf"); byte buf[] = new byte[1024]; int len; int lung = 0; while ((len = is.read(buf)) > 0) { System.out.print(len); lung += len; is.read(buf); os.write(buf, 0, len); } } }
Server side
I have a method that:
- receives an
InputStream as an argument, - creates a file with the same name and type of the source file.
The following code implements a test method for obtaining a specific PDF file.
@PUT @Path("/upload") @Consumes("application/pdf") public Response uploadMaterial(InputStream is) throws IOException { String name = "info"; String type = "exerc"; String description = "not defined"; Integer c = 10; Integer p = 131; File f = null; try { f = new File("welcome.pdf"); OutputStream out = new FileOutputStream(f); byte buf[] = new byte[1024]; int len; while ((len = is.read(buf)) > 0) out.write(buf, 0, len); out.close(); is.close(); System.out.println("\nFile is created........"); } catch (IOException e) { throw new WebApplicationException(Response.Status.BAD_REQUEST); }
This implementation only works with text files. If I try to send a simple PDF, the resulting file cannot be read (after I saved it to disk).
How can I satisfy my requirements? Can someone suggest me a solution?
source share