【问题标题】:How to send PUT, DELETE HTTP request in HttpURLConnection?如何在 HttpURLConnection 中发送 PUT、DELETE HTTP 请求?
【发布时间】:2010-11-06 06:22:08
【问题描述】:

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

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

【问题讨论】:

  • 你能告诉我们你尝试使用的代码吗?

标签: java httpurlconnection put http-delete


【解决方案1】:

执行 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 删除:

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

【讨论】:

  • 是的。所有这些都是可能的,但实际上取决于您的邮件/博客提供商支持的 API。
  • 您好,我遇到了delete 的问题。当我在这里运行此代码时,实际上什么也没发生,请求没有发送。同样的情况是当我在做post 请求时,但我可以使用例如httpCon.getContent() 来触发请求。但是httpCon.connect() 不会触发我机器中的任何内容:-)
  • 在上面的例子中,我相信你需要在最后调用 httpCon.getInputStream() 才能使请求真正被发送。
  • 我得到了“java.net.ProtocolException: DELETE does not support writing”
  • @edisusanto 指定的资源(由 URL 表示)是要删除的数据。
【解决方案2】:

这对我来说是这样的:

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

【讨论】:

    【解决方案3】:
    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
    }
    

    【讨论】:

    • 获取 'java.io.IOException: unsupported method: put' inJ2me sdk logger
    【解决方案4】:

    我同意 @adietisheim 和其他建议 HttpClient 的人的观点。

    我花了一些时间尝试使用 HttpURLConnection 对休息服务进行简单的调用,但它并没有说服我,之后我尝试使用 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 的问题,但您的回答对我有所帮助。
    • @Deprecated 使用 HttpClientBuilder 代替
    【解决方案5】:

    UrlConnection 是一个难用的 API。 HttpClient 是迄今为止更好的 API,它可以让您避免浪费时间搜索如何实现某些事情,比如这个 stackoverflow 问题完美地说明了这一点。我在几个 REST 客户端中使用了 jdk HttpUrlConnection 之后写了这个。 此外,在可扩展性功能(如线程池、连接池等)方面,HttpClient 更胜一筹

    【讨论】:

      【解决方案6】:

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

      【讨论】:

        【解决方案7】:

        甚至休息模板也可以是一个选项:

        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 上看到的最好的答案之一。
        【解决方案8】:

        删除和放置请求有一个简单的方法,您可以通过在您的发布请求中添加“_method”参数并为其值写入“PUT”或“DELETE”来实现!

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-01-10
          • 1970-01-01
          • 2012-07-09
          • 1970-01-01
          • 2015-07-10
          • 1970-01-01
          相关资源
          最近更新 更多