I am trying to upload a file using PUT method. I have been advised before to use POST and do a multipart upload but my web service only allows GET, PUT, PATCH, DELETE, HEAD and OPTIONS. And the main reason for that is that I am updating the JSON array that contains id, target, source, file. Now I just have to update the file part in the web service i.e. I have to upload the file there.
Here is my code:
URLConnection urlconnection = null;
try{
File file = new File("/Users/pathtofile/file.pdb");
URL url = new URL("http://example.website/api/jobs/5/");
urlconnection = url.openConnection();
urlconnection.setDoOutput(true);
urlconnection.setDoInput(true);
if (urlconnection instanceof HttpURLConnection) {
try {
((HttpURLConnection)urlconnection).setRequestMethod("PUT");
((HttpURLConnection)urlconnection).setRequestProperty("Content-Type",
"application/json");
((HttpURLConnection)urlconnection).connect();
} catch (ProtocolException e) {
// TODO Auto-generated catch block
System.out.println("ProtocolException");
e.printStackTrace();
}
}
BufferedOutputStream bos = new BufferedOutputStream(urlconnection
.getOutputStream());
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
file));
int i;
// read byte by byte until end of stream
while ((i = bis.read()) >= 0) {
bos.write(i);
}
bos.close();
// Getting error here (Bad request).
System.out.println(((HttpURLConnection)urlconnection).getResponseMessage());
} catch(Exception e) {
System.out.println("Exception");
e.printStackTrace();
}
try {
InputStream inputStream;
int responseCode = ((HttpURLConnection)urlconnection).getResponseCode();
if ((responseCode >= 200) && (responseCode <= 202)) {
inputStream = ((HttpURLConnection)urlconnection).getInputStream();
int j;
while ((j = inputStream.read()) >= 0) {
System.out.println(j);
}
} else {
System.out.println(responseCode);
inputStream = ((HttpURLConnection)urlconnection).getErrorStream();
System.out.println(inputStream);
}
((HttpURLConnection)urlconnection).disconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("IOException");
e.printStackTrace();
}
And I get the following error:
Bad Request
400
Is there a way to send a file using PUT method? The file is going to be in a place lıke this:
{"target":["This field is required."],
"project":["This field is required."],
"option":["This field is required."],
"result_file":["No file was submitted."],
"com_status":["This field is required."]}
The above is output from curl PUT method that I tried without giving any parameters. And it also shows that the parameters are required in a JSON format.