Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 727
soumitra goswami Avatar asked Apr 05 '19 10:04

soumitra goswami


1 Answers

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.

like image 127
Tohid Dadashnezhad Avatar answered Oct 13 '22 18:10

Tohid Dadashnezhad