139

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

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

4

8 回答 8

183

要执行 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();
于 2009-06-26T20:24:36.203 回答
26

这就是它对我的工作方式:

HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("DELETE");
int responseCode = connection.getResponseCode();
于 2011-02-16T19:23:31.277 回答
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
}
于 2012-11-20T01:23:39.830 回答
12

我同意@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);
于 2012-05-17T13:52:32.333 回答
4

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

于 2012-03-15T13:29:25.700 回答
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();
}
于 2015-02-09T14:30:37.307 回答
2

甚至休息模板也可以是一种选择:

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();
于 2017-06-15T13:35:25.947 回答
0

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

于 2018-09-17T09:25:54.650 回答