Java 如何在 HttpURLConnection 中发送 PUT、DELETE HTTP 请求?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1051004/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to send PUT, DELETE HTTP request in HttpURLConnection?
提问by Matrix
I want to know if it is possible to send PUT, DELETE request (practically) through java.net.HttpURLConnection
to HTTP-based URL.
我想知道是否可以将 PUT、DELETE 请求(实际上)发送java.net.HttpURLConnection
到基于 HTTP 的 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.
我已经阅读了很多描述如何发送 GET、POST、TRACE、OPTIONS 请求的文章,但我仍然没有找到任何成功执行 PUT 和 DELETE 请求的示例代码。
回答by Clint
I would recommend Apache HTTPClient.
我会推荐 Apache HTTPClient。
回答by Matthew Murdoch
To perform an HTTP PUT:
要执行 HTTP PUT:
URL url = new URL("http://www.example.com/resource");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("PUT");
OutputStreamWriter out = new OutputStreamWriter(
httpCon.getOutputStream());
out.write("Resource content");
out.close();
httpCon.getInputStream();
To perform an HTTP DELETE:
要执行 HTTP DELETE:
URL url = new URL("http://www.example.com/resource");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestProperty(
"Content-Type", "application/x-www-form-urlencoded" );
httpCon.setRequestMethod("DELETE");
httpCon.connect();
回答by Eli Heifetz
This is how it worked for me:
这对我来说是这样的:
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("DELETE");
int responseCode = connection.getResponseCode();
回答by adietisheim
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
UrlConnection 是一个很难使用的 API。HttpClient 是迄今为止更好的 API,它可以让您免于浪费时间搜索如何实现某些事情,例如这个 stackoverflow 问题完美地说明了这一点。我在几个 REST 客户端中使用了 jdk HttpUrlConnection 之后写了这个。此外,当谈到可扩展性功能(如线程池、连接池等)时,HttpClient 更胜一筹
回答by Alvaro
I agree with @adietisheim and the rest of people that suggest HttpClient.
我同意@adietisheim 和其他建议使用 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.
我花了一些时间尝试使用 HttpURLConnection 对休息服务进行简单的调用,但它并没有说服我,之后我尝试使用 HttpClient,它确实更容易、更容易理解和更好。
An example of code to make a put http call is as follows:
进行 put http 调用的代码示例如下:
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPut putRequest = new HttpPut(URI);
StringEntity input = new StringEntity(XML);
input.setContentType(CONTENT_TYPE);
putRequest.setEntity(input);
HttpResponse response = httpClient.execute(putRequest);
回答by Benjamin Twilight
public HttpURLConnection getHttpConnection(String url, String type){
URL uri = null;
HttpURLConnection con = null;
try{
uri = new URL(url);
con = (HttpURLConnection) uri.openConnection();
con.setRequestMethod(type); //type: POST, PUT, DELETE, GET
con.setDoOutput(true);
con.setDoInput(true);
con.setConnectTimeout(60000); //60 secs
con.setReadTimeout(60000); //60 secs
con.setRequestProperty("Accept-Encoding", "Your Encoding");
con.setRequestProperty("Content-Type", "Your Encoding");
}catch(Exception e){
logger.info( "connection i/o failed" );
}
return con;
}
Then in your code :
然后在你的代码中:
public void yourmethod(String url, String type, String reqbody){
HttpURLConnection con = null;
String result = null;
try {
con = conUtil.getHttpConnection( url , type);
//you can add any request body here if you want to post
if( reqbody != null){
con.setDoInput(true);
con.setDoOutput(true);
DataOutputStream out = new DataOutputStream(con.getOutputStream());
out.writeBytes(reqbody);
out.flush();
out.close();
}
con.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String temp = null;
StringBuilder sb = new StringBuilder();
while((temp = in.readLine()) != null){
sb.append(temp).append(" ");
}
result = sb.toString();
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
logger.error(e.getMessage());
}
//result is the response you get from the remote side
}
回答by Carlos Sirvent
For doing a PUT in HTML correctly, you will have to surround it with try/catch:
为了在 HTML 中正确执行 PUT,您必须用 try/catch 包围它:
try {
url = new URL("http://www.example.com/resource");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("PUT");
OutputStreamWriter out = new OutputStreamWriter(
httpCon.getOutputStream());
out.write("Resource content");
out.close();
httpCon.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
回答by Gloria Rampur
Even Rest Template can be an option :
甚至休息模板也可以是一个选项:
String payload = "<?xml version=\"1.0\" encoding=\"UTF-8\"?<CourierServiceabilityRequest>....";
RestTemplate rest = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/xml");
headers.add("Accept", "*/*");
HttpEntity<String> requestEntity = new HttpEntity<String>(payload, headers);
ResponseEntity<String> responseEntity =
rest.exchange(url, HttpMethod.PUT, requestEntity, String.class);
responseEntity.getBody().toString();
回答by Mohamad Rostami
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!
有一种简单的删除和放置请求的方法,您可以简单地通过_method
在您的发布请求中添加一个“ ”参数并为其值写入“ PUT
”或“ DELETE
”来实现!