Getting "400 This page expects a form submission" when making a rest call to trigger a Jenkins Job
Asked Answered
C

1

27

I need to trigger a Jenkins Job from my Java code.The Jenkins API expects a application/x-www-form-urlencoded Content-Type and I am able to trigger the job (using Basic AUTH) from Postman Rest Client.However When I try to the same from my java code,I get this exception- HttpClientErrorException: 400 This page expects a form submission:

Exception while triggerring jenkins {} 400 This page expects a form submission
org.springframework.web.client.HttpClientErrorException: 400 This page expects a form submission
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:108)
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:708)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:661)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:621)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:539)

I am using RestTemplate to call the api.I have set the Content Type header:

headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

and set the form parameters in a map

MultiValueMap<String, String> map = new 
LinkedMultiValueMap<String, String>();
map.add("name", "value");
map.add("field2,"value");
map.add("json","a json string");

and the request as:

HttpEntity<MultiValueMap<String, String>> request = new 
HttpEntity<MultiValueMap<String, String>>(map, headers);

finally making the call as :

 ResponseEntity<String> response = 
    restTemplate.exchange(url,HttpMethod.POST, request, String.class);

One thing to note is the expected response is text/html which I want to store in a string and parse to get some values.

Cooking answered 5/4, 2019 at 10:21 Comment(1)
So how did you solve this?Eponymous
S
36

I had this problem too. Finally, I found that if your job has parameters and you call /build, this causes 400 bad request error. You must call /buildWithParameters even if all the parameters have default values.

Suckerfish answered 16/2, 2021 at 19:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.