删除资源

   public static void delete (String urlString, String contentType) throws IOException {
        HttpURLConnection connection = null;
    
        try {
            URL url = new URL(urlString);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setRequestMethod("DELETE");
            connection.setRequestProperty("Content-Type", contentType);
    
            Map<String, List<String>> map = connection.getHeaderFields();
            StringBuilder sb = new StringBuilder();
            Iterator<Map.Entry<String, String>> iterator = responseHeader.entrySet().iterator();
            while(iterator.hasNext())
            {
                Map.Entry<String, String> entry = iterator.next();
                sb.append(entry.getKey());
                sb.append('=').append('"');
                sb.append(entry.getValue());
                sb.append('"');
                if(iterator.hasNext())
                {
                    sb.append(',').append(' ');
                }
            }
            System.out.println(sb.toString());
    
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) connection.disconnect();
        }
    }

这将删除指定 URL 中的资源,然后打印响应头。

这个怎么运作

  • 我们从 URL 获得 HttpURLConnection
  • 使用 setRequestProperty 设置内容类型,默认情况下是 application/x-www-form-urlencoded
  • setDoInput(true) 告诉连接我们打算使用 URL 连接进行输入。
  • setRequestMethod("DELETE") 执行 HTTP DELETE

最后我们打印服务器响应头。