本文介绍了如何在JAVA中的HttpURLConnection中发送PUT,DELETE HTTP请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有Restful WebServices,我发送POST和GET HTTP请求,如何使用JAVA在httpURLConection中发送PUT和DELTE请求HTTP。
I have Restful WebServices, and i send POST and GET HTTP request, how to send PUT and DELTE request HTTP in httpURLConection with JAVA.
推荐答案
PUT
URL url = null;
try {
url = new URL("http://localhost:8080/putservice");
} catch (MalformedURLException exception) {
exception.printStackTrace();
}
HttpURLConnection httpURLConnection = null;
DataOutputStream dataOutputStream = null;
try {
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpURLConnection.setRequestMethod("PUT");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
dataOutputStream.write("hello");
} catch (IOException exception) {
exception.printStackTrace();
} finally {
if (dataOutputStream != null) {
try {
dataOutputStream.flush();
dataOutputStream.close();
} catch (IOException exception) {
exception.printStackTrace();
}
}
if (httpsURLConnection != null) {
httpsURLConnection.disconnect();
}
}
DELETE
URL url = null;
try {
url = new URL("http://localhost:8080/deleteservice");
} catch (MalformedURLException exception) {
exception.printStackTrace();
}
HttpURLConnection httpURLConnection = null;
try {
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
httpURLConnection.setRequestMethod("DELETE");
System.out.println(httpURLConnection.getResponseCode());
} catch (IOException exception) {
exception.printStackTrace();
} finally {
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
这篇关于如何在JAVA中的HttpURLConnection中发送PUT,DELETE HTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!