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

时间:2022-03-08 20:16:10

I want to know if it is possible to send PUT, DELETE request (practically) through java.net.HttpURLConnection to HTTP-based URL.

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

I have read so many articles describing that how to send GET, POST, TRACE, OPTIONS requests but I still haven't found any sample code which successfully performs PUT and DELETE requests.

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

8 个解决方案

#1


153  

To perform an HTTP PUT:

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

To perform an HTTP DELETE:

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

#2


20  

This is how it worked for me:

这就是它对我的作用:

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

#3


8  

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

Then in your code :

然后在你的代码中:

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
}

#4


7  

I agree with @adietisheim and the rest of people that suggest HttpClient.

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

I spent time trying to make a simple call to rest service with HttpURLConnection and it hadn't convinced me and after that I tried with HttpClient and it was really more easy, understandable and nice.

我花了很多时间试图用HttpURLConnection来简单地调用rest服务,但它并没有说服我,之后我尝试了HttpClient,它真的更简单,可以理解和友好。

An example of code to make a put http call is as follows:

编写一个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);

#5


3  

UrlConnection is an awkward API to work with. HttpClient is by far the better API and it'll spare you from loosing time searching how to achieve certain things like this * question illustrates perfectly. I write this after having used the jdk HttpUrlConnection in several REST clients. Furthermore when it comes to scalability features (like threadpools, connection pools etc.) HttpClient is superior

UrlConnection是一个笨拙的API。HttpClient是一个更好的API,它会让你不用浪费时间搜索如何实现某些东西,比如*的问题。我在几个REST客户机中使用jdk HttpUrlConnection之后编写了这个代码。此外,当涉及到可伸缩性特性(如线程池、连接池等)时,HttpClient更高级。

#6


3  

For doing a PUT in HTML correctly, you will have to surround it with try/catch:

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

#7


1  

I would recommend Apache HTTPClient.

我推荐Apache HTTPClient。

#8


0  

Even Rest Template can be an option :

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

String payload = "<?xml version=\"1.0\" encoding=\"UTF-8\"?<CourierServiceabilityRequest>....";
    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();

#1


153  

To perform an HTTP PUT:

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

To perform an HTTP DELETE:

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

#2


20  

This is how it worked for me:

这就是它对我的作用:

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

#3


8  

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

Then in your code :

然后在你的代码中:

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
}

#4


7  

I agree with @adietisheim and the rest of people that suggest HttpClient.

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

I spent time trying to make a simple call to rest service with HttpURLConnection and it hadn't convinced me and after that I tried with HttpClient and it was really more easy, understandable and nice.

我花了很多时间试图用HttpURLConnection来简单地调用rest服务,但它并没有说服我,之后我尝试了HttpClient,它真的更简单,可以理解和友好。

An example of code to make a put http call is as follows:

编写一个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);

#5


3  

UrlConnection is an awkward API to work with. HttpClient is by far the better API and it'll spare you from loosing time searching how to achieve certain things like this * question illustrates perfectly. I write this after having used the jdk HttpUrlConnection in several REST clients. Furthermore when it comes to scalability features (like threadpools, connection pools etc.) HttpClient is superior

UrlConnection是一个笨拙的API。HttpClient是一个更好的API,它会让你不用浪费时间搜索如何实现某些东西,比如*的问题。我在几个REST客户机中使用jdk HttpUrlConnection之后编写了这个代码。此外,当涉及到可伸缩性特性(如线程池、连接池等)时,HttpClient更高级。

#6


3  

For doing a PUT in HTML correctly, you will have to surround it with try/catch:

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

#7


1  

I would recommend Apache HTTPClient.

我推荐Apache HTTPClient。

#8


0  

Even Rest Template can be an option :

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

String payload = "<?xml version=\"1.0\" encoding=\"UTF-8\"?<CourierServiceabilityRequest>....";
    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();