【发布时间】:2014-08-27 16:46:57
【问题描述】:
我正在编写一个需要向 url 发送 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。知道有什么问题吗?
【问题讨论】:
标签: java httpurlconnection put