'POST request does not work in Java client but works in postman
I am trying to execute a POST request to a REST endpoint and it fails when executing under Java code. The response I am getting back has a status 403 forbidden.
I am using apache HttpClient. Here is the code I am using:
var postRequest = new HttpPost(myUrl);
postRequest.addHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN_VALUE);
postRequest.addHeader("x-env", environment);
postRequest.addHeader("apikey", myApiKey);
The headers are set properly and have exactly the same values as in Postman.From what I seen on similar posts not having the "User-Agent" header could cause this. Setting that did not solve my issue and I am running out of ideas. In fact I manually set all the headers from Postman and still no luck.
When executing a GET to the same URL context from Java it works. Also some JS client accessing exactly the same endpoint with the same HTTP headers also works. here is the JS code:
const cnf = {
headers: {
'x-env': 'dev',
apikey: this.myApyKey,
'Content-Type': 'text/plain',
},
};
const data = myRequestBody;
try {
const res = await axios.post(this.apiPath, data, cnf as AxiosRequestConfig);
....
Thank you in advance for your inputs.
Solution 1:[1]
Try checking whether your code allows CORS requests? Because in POSTMAN, even if backend does not allow CORS requests, It still executes the api. But that is not the case with any programming languages.
Solution 2:[2]
The URL I was trying to post to was poorly configured in AWS. I did not notice the URL end point ended up with a "/" but in my Java code I was trying to access the same URL without a forward slash.
// So this worked:
https://my/path/to/post/resource/
// But this did not
https://my/path/top/post/resource
Configuring the Route 53 to map both paths with and without a forward slash fixed the issue. Publishing this as an answer so others can check it out if getting the same.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Julian |