java - 如何在JAVA的HttpURLConnection中发送PUT、DELETE HTTP请求

标签 java http rest httpurlconnection

我有 Restful WebServices,我发送 POST 和 GET HTTP 请求,如何使用 JAVA 在 httpURLConection 中发送 PUT 和 DELTE 请求 HTTP。

最佳答案

放置

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();
    }
}

删除

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 - 如何在JAVA的HttpURLConnection中发送PUT、DELETE HTTP请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19320555/

相关文章:

javascript - 计算发送 Ajax 请求和接收应答之间的时间

python - 如何自定义 Tornado 的访问日志

javascript - 使用 jQuery DataTables 自定义 REST 数据源

java - WebParam 不允许使用 XmlElement 注释

java - 使用 .app 运行自定义安装脚本

javascript - $http 获取逻辑只允许 200 OK

java - 验证 PUT 操作的资源

java - 实现 Spring Data 存储库的自定义方法并通过 REST 公开它们

java - 抛出和捕获异常

java - 无法使用Tomcat和Maven的tomcat7-websocket插件启动WebSocket容器