Reputation: 1139
I am trying to POST request without body to some REST service url.
HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Length", "0"); //tried with/without
con.setDoOutput(true); //tried with/without
con.connect();
The response is:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML>
<HEAD>
<TITLE>Length Required</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii">
</HEAD>
<BODY>
<h2>Length Required</h2>
<hr>
<p>HTTP Error 411. The request must be chunked or have a content length.</p>
</BODY>
</HTML>
(sending POST to same link with POSTMAN worked)
Upvotes: 4
Views: 10277
Reputation: 63
In my case, adding
conn.getOutputStream();
solved the 411 response code. Without actually writing anything to the output stream.
Upvotes: 1
Reputation: 5870
So far, the only way I found to actually trigger the request is to call HttpURLConnection.getInputStream()
, even if there is no response or you don't care about it:
HttpURLConnection c= (HttpURLConnection) new URL("https://host.com/api/...").openConnection();
c.setRequestMethod("POST");
c.getInputStream().close();
Next caveat: If the server answers with a 302 redirect, like jenkins does, you might have to disable the redirect following to avoid getting a 403 exception:
HttpURLConnection c = (HttpURLConnection) new URL("https://host.com/jenkins/reload").openConnection();
c.setInstanceFollowRedirects(false);
c.setRequestMethod("POST");
c.addRequestProperty("Authorization", "Basic " + Base64.toBase64String("user:apiToken".getBytes()));
c.getInputStream().close();
Upvotes: 0
Reputation: 140
I think your URL have some parameters, which are added in URL after '?' symbol. So when you use parameters you have to declare length.
Here you can add parameters and get length of it.
String urlParameters =
"User=" + URLEncoder.encode("bhavik", "UTF-8") +
"&passwd=" + URLEncoder.encode("1234", "UTF-8")+
Set your own parameters and value in above code and then use this line for getting length of string.
conn.setRequestProperty("Content-Length", ""+Integer.toString(urlParameters.getBytes().length));
This will work for you, because i had the same issue and i resolved it like this only.
Upvotes: 0