如何在HttpURLConnection中发送PUT、DELETE请求?

143

我想知道是否可以通过java.net.HttpURLConnection向基于HTTP的URL发送PUT和DELETE请求(实际上)。

我已经阅读了许多文章,描述了如何发送GET、POST、TRACE、OPTIONS请求,但我仍然没有找到任何成功执行PUT和DELETE请求的示例代码。


2
你可以展示一下你尝试使用的代码吗? - akarnokd
8个回答

188

执行 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();

执行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();

1
是的,所有这些都是可能的,但真正取决于您的邮件/博客提供商所支持的API。 - Matthew Murdoch
6
你好,我在使用“delete”时遇到了麻烦。当我按照这里的代码执行时,什么也没有发生,请求也没有发送。当我进行“post”请求时,情况也是一样的,但是在那里,我可以使用例如“httpCon.getContent()”来触发请求。但是在我的电脑上,“httpCon.connect()”没有触发任何事情 :-) - ryskajakub
8
在上面的例子中,我认为你需要在最后调用httpCon.getInputStream()来实际发送请求。 - Eric Smith
3
我收到了 "java.net.ProtocolException: DELETE 不支持写入" 的错误信息。 - Kimo_do
1
@edisusanto,所指定的资源(由URL指示)是将被删除的数据。 - Matthew Murdoch
显示剩余15条评论

26

这是对我而言的操作步骤:

HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("DELETE");
int responseCode = connection.getResponseCode();

13
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;
}

然后在您的代码中:

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
}

在J2ME SDK日志记录器中出现“java.io.IOException: unsupported method: put”错误 - CodeToLife

12

我同意@adietisheim和其他建议使用HttpClient的人。

我曾尝试使用HttpURLConnection对REST服务进行简单调用,但并没有说服我。后来我尝试了HttpClient,它更加容易、易于理解和友好。

下面是一个用于进行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);

只是想说谢谢你。我花了很多时间尝试让我的代码使用HttpURLConnection工作,但一直遇到一个奇怪的错误,具体来说是:cannot retry due to server authentication, in streaming mode。按照你的建议做对我有用。我意识到这并不完全回答了问题,它要求使用HttpURLConnection,但是你的答案帮助了我。 - Tom Catullo
@Deprecated 使用 HttpClientBuilder 替代 - Waldemar Wosiński

4

要正确地在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();
}

4

UrlConnection是一个很难使用的API。HttpClient是迄今为止更好的API,它将使您免于浪费时间搜索如何实现某些东西,就像这个stackoverflow问题完美地说明的那样。在使用jdk HttpUrlConnection时,我写下这篇文章,以便在多个REST客户端中使用。 此外,当涉及可扩展性功能(如线程池、连接池等)时,HttpClient更加优越。


2
甚至 Rest Template 也可以是一个选择:
String payload = "<?xml version=\"1.0\" encoding=\"UTF-8\"?<RequestDAO>....";
    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();

这是我在SO上看到的最好的答案之一。 - thonnor

0

有一个简单的方法可以进行删除和修改请求,只需在您的POST请求中添加一个"_method"参数,并将其值写为"PUT"或"DELETE"即可!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接