users@jersey.java.net

Java equivalent of curl -F

From: Andrew Hopkinson <Andrew.Hopkinson_at_Sun.COM>
Date: Tue, 13 Oct 2009 10:32:59 +0100

Hi,

I have been trying, unsuccessfully, to build a simple class that
executes the equivalent of the following:

curl -F "contents=@<yourFilename>" -X POST http://localhost:8080/spaces/rest/store/space/<yourSpaceName>/artifact

I have tried a number of options based around MultivalueMaps and
MulitPart with no luck. I have tried the following and permutations of
it but am still stuck so if anyone has any suggestion I would appreciate
any hints.


            String filename = args[0].replaceAll("\\\\", "/");
            int pos = filename.lastIndexOf("/");
            MultivaluedMap formData = new MultivaluedMapImpl();
// formData.add("name", "contents");
            formData.add("filename", filename.substring(pos+1));

            file = new File(args[0]);
            fis = new FileInputStream(file);
            byte[] fileBytes = new byte[(int) file.length()];
            fis.read(fileBytes);
// System.out.println("File Bytes : " + new String(fileBytes));
           
            multiPart = new MultiPart().
                    bodyPart(formData,
MediaType.APPLICATION_FORM_URLENCODED_TYPE).
                    bodyPart(fileBytes,
MediaType.APPLICATION_OCTET_STREAM_TYPE);

            System.out.println("MultiPart = " + multiPart.getHeaders());

            response =
webResource.type(MediaType.MULTIPART_FORM_DATA_TYPE).accept(MediaType.WILDCARD_TYPE).post(ClientResponse.class,
multiPart);
// response =
webResource.type("multipart/mixed").post(ClientResponse.class, multiPart);
            System.out.println("Response = " + response);

Thanks

Andrew