我正在编写一个需要向网址发送PUT请求的java程序。我通过使用
在cURL中实现了这一壮举cURL -k -T myFile -u username:password https://www.mywebsite.com/myendpoint/
但是,如果我只是在java代码中执行请求会好得多。到目前为止,我的java代码是
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();
}
我收到411返回码。我明确地设定了内容长度,所以我没有得到它。回复的标题是:
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
起初,我发送带有标题的正文,并收到409错误。所以,我看了一下cURL在做什么。他们单独发送标题,期望100返回代码。一旦他们得到100响应,他们发送身体并获得200响应。
我在java中发送的标题似乎与cURL发送的标题相同,但我得到411返回代码而不是100.任何想法是什么错误?
答案 0 :(得分:0)
您应该查看http客户端库,例如Apache HTTP Components。这样你就可以在更高的水平上工作,并且希望不必担心计算内容长度。
答案 1 :(得分:0)
替换
java.net.URL url = new java.net.URL("https://www.mywebsite.com/" + folder);
与
java.net.URL url = new java.net.URL("https://www.mywebsite.com/" + folder + file.getName());
此外,您无需等待100响应即可发送正文。