如何在HttpURLConnection中发送PUT、DELETE HTTP请求?
我想知道是否可以通过 java.net.HttpURLConnection 向基于 HTTP 的 URL 发送 PUT、DELETE 请求(实际上)。
我读过很多文章描述如何发送 GET、POST、TRACE、OPTIONS 请求,但我仍然没有找到任何成功执行 PUT 和 DELETE 请求的示例代码。
I want to know if it is possible to send PUT, DELETE request (practically) through java.net.HttpURLConnection
to HTTP-based URL.
I have read so many articles describing that how to send GET, POST, TRACE, OPTIONS requests but I still haven't found any sample code which successfully performs PUT and DELETE requests.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
要执行 HTTP PUT:
要执行 HTTP DELETE:
To perform an HTTP PUT:
To perform an HTTP DELETE:
这对我来说是这样的:
This is how it worked for me:
然后在你的代码中:
Then in your code :
我同意 @adietisheim 和其他建议 HttpClient 的人的观点。
我花了一些时间尝试使用 HttpURLConnection 对休息服务进行简单的调用,但它并没有说服我,之后我尝试使用 HttpClient,它确实更容易、更容易理解、也更好。
进行 put http 调用的代码示例如下:
I agree with @adietisheim and the rest of people that suggest HttpClient.
I spent time trying to make a simple call to rest service with HttpURLConnection and it hadn't convinced me and after that I tried with HttpClient and it was really more easy, understandable and nice.
An example of code to make a put http call is as follows:
UrlConnection 是一个很难使用的 API。 HttpClient 是迄今为止更好的 API,它可以让您免于浪费时间搜索如何实现某些事情,就像这个 stackoverflow 问题完美地说明了这一点。 我在几个 REST 客户端中使用了 jdk HttpUrlConnection 后写了这篇文章。
此外,当涉及到可扩展性功能(如线程池、连接池等)时,HttpClient 更胜一筹
UrlConnection is an awkward API to work with. HttpClient is by far the better API and it'll spare you from loosing time searching how to achieve certain things like this stackoverflow question illustrates perfectly. I write this after having used the jdk HttpUrlConnection in several REST clients.
Furthermore when it comes to scalability features (like threadpools, connection pools etc.) HttpClient is superior
为了正确地在 HTML 中执行 PUT,您必须用 try/catch 包围它:
For doing a PUT in HTML correctly, you will have to surround it with try/catch:
甚至 Rest Template 也可以是一个选项:
Even Rest Template can be an option :
删除和放置请求有一个简单的方法,您只需在发布请求中添加“
_method
”参数并写入“PUT
”或“删除
”的价值!there is a simple way for delete and put request, you can simply do it by adding a "
_method
" parameter to your post request and write "PUT
" or "DELETE
" for its value!