Java:使用 HttpURLConnection 的 HTTP PUT
如何执行 HTTP PUT?我正在使用的类似乎认为它正在执行 PUT,但端点将其视为我执行了 GET。我做错了什么吗?
URL url = new URL("https://...");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("PUT");
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(xmlString);
writer.close();
System.out.println(conn.getRequestMethod());
String response = readInputStream(conn.getInputStream());
System.out.println(response);
正在打印:
PUT
<same content as doing a GET>
如果这个库可以工作,我宁愿不包含另一个库......
How do you do do an HTTP PUT? The class I'm using seems to think it is doing a PUT but the endpoint is treating it as if I did a GET. Am I doing anything wrong?
URL url = new URL("https://...");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("PUT");
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(xmlString);
writer.close();
System.out.println(conn.getRequestMethod());
String response = readInputStream(conn.getInputStream());
System.out.println(response);
Which is printing:
PUT
<same content as doing a GET>
I'd rather not include another library if this one could work...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有一种简单的方法可以找到答案:运行 Wireshark 并查看网络上实际发生的情况。我发现这是诊断此类问题的最可靠方法 - 您的客户端可能有错误,库可能有错误,服务器可能有错误,但 Wireshark 会告诉您到底发生了什么。
编辑:好的,对于 HTTPS 来说有点棘手。如果你在 Windows 上运行,你可以使用 Fiddler,它是一个代理 - 如果你能说服它,它可以处理 HTTPS您的客户端代码接受其证书,但这更具侵入性......以这种方式放置代理显然会改变流量的样子。
如果您可以通过 HTTP 与服务器的调试版本通信,那就更好了。这对于您的情况是否可行,或者服务器完全超出您的控制范围?
There's one easy way to find out: run Wireshark and see what's actually happening on the network. I've found that to be the most reliable way of diagnosing this sort of issue - your client could have bugs, the library could have bugs, the server could have bugs, but Wireshark will show you what's really happening.
EDIT: Okay, for HTTPS it's a little trickier. You can use Fiddler if you're running on Windows, which is a proxy - it can cope with HTTPS if you can persuade your client code to accept its certificate, but that's a little more intrusive... putting a proxy in the way clearly changes what the traffic looks like.
It would be better if you could talk to a debug version of the server over HTTP instead. Is that feasible in your case, or is the server completely outside your control?