How to send PUT, DELETE HTTP request in HttpURLConnection?

JavaHttpurlconnectionPutHttp Delete

Java Problem Overview


I want to know if it is possible to send PUT, DELETE request (practically) through java.net.HttpURLConnection to HTTP-based 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.

Java Solutions


Solution 1 - Java

To perform an 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:

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

Solution 2 - Java

This is how it worked for me:

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

Solution 3 - Java

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
}

Solution 4 - Java

I agree with @adietisheim and the rest of people that suggest 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.

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

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

Solution 5 - Java

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 stackoverflow 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

Solution 6 - Java

For doing a PUT in HTML correctly, you will have to surround it with 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();
}

Solution 7 - Java

Even Rest Template can be an option :

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

Solution 8 - Java

there is a simple way for delete and put request, you can simply do it by adding a "_method" parameter to your post request and write "PUT" or "DELETE" for its value!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMatrixView Question on Stackoverflow
Solution 1 - JavaMatthew MurdochView Answer on Stackoverflow
Solution 2 - JavaEli HeifetzView Answer on Stackoverflow
Solution 3 - JavaBenjamin TwilightView Answer on Stackoverflow
Solution 4 - JavaAlvaroView Answer on Stackoverflow
Solution 5 - JavaadietisheimView Answer on Stackoverflow
Solution 6 - JavaCarlos SirventView Answer on Stackoverflow
Solution 7 - JavaGloria RampurView Answer on Stackoverflow
Solution 8 - JavaMohamad RostamiView Answer on Stackoverflow