Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ionic-framework/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在HttpURLConnection中发送PUT、DELETE HTTP请求?_Java_Httpurlconnection_Put_Http Delete - Fatal编程技术网

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

Java 如何在HttpURLConnection中发送PUT、DELETE HTTP请求?,java,httpurlconnection,put,http-delete,Java,Httpurlconnection,Put,Http Delete,我想知道是否可以通过java.net.HttpURLConnection向基于HTTP的URL发送PUT、DELETE请求(实际上) 我读过很多文章,介绍如何发送GET、POST、TRACE和OPTIONS请求,但我仍然没有找到任何成功执行PUT和DELETE请求的示例代码。我建议使用Apache HTTPClient 要执行HTTP PUT,请执行以下操作: URL url = new URL("http://www.example.com/resource"); HttpURLConn

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


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

我建议使用Apache HTTPClient


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

    这就是它对我的作用:

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

    UrlConnection是一个很难使用的API。HttpClient是迄今为止最好的API,它将使您不必浪费时间来搜索如何实现某些事情,如stackoverflow问题所示。我是在几个REST客户机中使用jdk HttpUrlConnection之后写这篇文章的。
    此外,在可伸缩性功能(如线程池、连接池等)方面,HttpClient更具优势

    我同意@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);
    
    然后在代码中:

    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
    }
    

    为了正确地输入HTML,您必须用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();
    }
    

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

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

    String payload=“有一种简单的删除和放置请求的方法,您只需在post请求中添加一个“
    \u method
    ”参数,然后写入“
    put
    ”或“
    delete
    “为了它的价值

    你能告诉我们你试着使用的代码吗?是的。所有这些都是可能的,但实际上取决于您的邮件/博客提供商支持的API。您好,我遇到了
    delete
    的问题。当我在这里运行这段代码时,实际上什么都没有发生,请求没有被发送。当我执行
    post
    请求时也会遇到同样的情况,但在那里我可以使用触发请求的
    httpCon.getContent()
    。但是
    httpCon.connect()
    不会在我的机器中触发任何东西:-)在上面的示例中,我相信您需要在最后调用httpCon.getInputStream()以使请求实际被发送。我得到了“java.net.ProtocolException:DELETE不支持将@edisusanto写入指定资源(由URL指示)是将被删除的数据。为什么推荐HTTPClient?它很大。我的意思是-在大小上。@jayarjo,它是Android SDK的一部分。@Zamel:Android到底在哪里进入图片?@talonx:我不知道。我的错误。我埋头于Android开发,因此产生了困惑。当OP明确表示应该使用HttpUrlConnection时,那么为什么要使用HttpClient?我只是想说声谢谢。花了很多时间试图使用
    HttpURLConnection
    让我的代码正常工作,但一直遇到一个奇怪的错误,特别是:
    在流模式下,由于服务器身份验证而无法重试。听你的劝告对我有用。我意识到这并不能完全回答这个问题,这个问题要求使用
    HttpURLConnection
    ,但你的回答帮助了我。@不推荐使用HttpClientBuilder而不是使用获取“java.io.IOException:unsupported method:put”inJ2me sdk logger这是我在这方面看到的最好答案之一。
    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();