在HttpURLConnection中发送PUT,DELETE HTTP请求 [英] Send PUT, DELETE HTTP request in HttpURLConnection

查看:192
本文介绍了在HttpURLConnection中发送PUT,DELETE HTTP请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用java下面的代码创建了Web服务调用。现在我需要进行删除和执行操作。

I have created web service call using java below code. Now I need to make delete and put operations to be perform.

URL url = new URL("http://example.com/questions");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod( "POST" );
conn.setRequestProperty("Content-Type", "application/json");

OutputStream os = conn.getOutputStream();
os.write(jsonBody.getBytes());
os.flush();

当我添加以下代码来执行DELETE操作时,它会出错:

When I add below code to perform DELETE action it gives errors saying:


java.net.ProtocolException:HTTP方法DELETE不支持输出。

java.net.ProtocolException: HTTP method DELETE doesn't support output.



conn.setRequestMethod( "DELETE" );

那么如何执行删除和放置请求?

So how to perform delete and put requests?

推荐答案

PUT 示例使用 HttpURLConnection

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 示例使用 HttpURLConnection

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

这篇关于在HttpURLConnection中发送PUT,DELETE HTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆