I am writing a java program that needs to send a PUT request to a url. I have achieved this feat in cURL by using
cURL -k -T myFile -u username:password https://www.mywebsite.com/myendpoint/
However, it would be much better if I could simply perform the request in the java code. So far, my java code is
public static Integer sendFileToEndpoint(java.io.File file, String folder) throws Exception
{
java.net.URL url = new java.net.URL("https://www.mywebsite.com/" + folder);
java.net.HttpURLConnection conn = (java.net.HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
java.io.FileInputStream fis = new java.io.FileInputStream(file);
byte [] fileContents = org.apache.commons.io.IOUtils.toByteArray(fis);
String authorization = "Basic " + new String(new org.apache.commons.codec.binary.Base64().encode("username:password".getBytes()));
conn.setRequestMethod("PUT");
conn.setRequestProperty("Authorization", authorization);
conn.setRequestProperty("User-Agent","curl/7.37.0");
conn.setRequestProperty("Host", "www.mywebsite.com");
conn.setRequestProperty("Accept","*/*");
conn.setRequestProperty("Content-Length", String.valueOf(fileContents.length));
conn.setRequestProperty("Expect","100-continue");
if(conn.getResponseCode() == 100)
{
//not sure what to do here, but I'm not getting a 100 return code anyway
java.io.OutputStream out = conn.getOutputStream();
out.write(fileContents);
out.close();
}
return conn.getResponseCode();
}
I am getting a 411 return code. I am explicitly setting content length, so I don't get it. The header of the response is:
HTTP/1.1 411 Length Required
Content-Type:text/html; charset=us-ascii
Server:Microsoft-HTTPAPI/2.0
Date:Wed, 27 Aug 2014 16:32:02 GMT
Connection:close
Content-Length:344
At first, I was sending the body with the header and was getting a 409 error. So, I looked at what cURL was doing. They send the header alone, expecting a 100 return code. Once they get the 100 response, they send the body and get a 200 response.
The header I'm sending in java seems to be equal to the one sent by cURL, yet I get a 411 return code instead of a 100. Any idea what's wrong?
Replace
java.net.URL url = new java.net.URL("https://www.mywebsite.com/" + folder);
with
java.net.URL url = new java.net.URL("https://www.mywebsite.com/" + folder + file.getName());
Also, you do not need to wait for the 100 response to send the body.