I want to send a post request in Groovy using HttpURLConnection and I can't get it to work.
HttpURLConnection conn = new URL("https://url").openConnection()
conn.setDoOutput(true)
conn.setRequestMethod("POST")
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded")
conn.getOutputStream().write("client_id=client_id&username=username&password=password&scope=api&grant_type=password".getBytes("UTF-8"))
assert conn.getResponseCode() == 403
I have tried other ways: Postman, Java OkHttp, Python requests and Java Unirest and they all worked instantly. Here is the working code for Java Unirest (credits to Postman):
import kong.unirest.HttpResponse
HttpResponse<String> response = Unirest.post("https://url")
.header("Content-Type", "application/x-www-form-urlencoded")
.field("client_id", "client_id")
.field("username", "username")
.field("password", "password")
.field("scope", "api")
.field("grant_type", "password")
.asString();
I know this is not a particular Groovy question, but maybe somebody knows why my HttpURLConnection version doesn't work?
How about