I am trying to send a http GET request. This is what the request looks like:
https://example.com/verify?name="A"&grade="A"
Header: "myheader":"abcde1213"
This is a custom header that authenticates the sender of this request.
I tried this using Postman and curl and it works. However, when I try to do it in code using HttpURLConnection in Android, I always get a 401 error from the server - indicating that authentication of the above key did not work.
What I added in code:
URL obj = new URL(GetURL);
HttpURLConnection con = obj.openConnection();
con.setRequestMethod("GET");
con.addRequestProperty("myheader","abcde1213");
I even did a getRequestProperty("myheader") and verified it returns the right value.
However, the server is not picking up this value and is giving me a 401 error. On further investigation, it turns out http request parameters and headers are different. The above addRequestParameter or setRequestParameter functions only add or update the http request parameters and do not set the headers.
From a quick online search, I do not see any suitable method in HttpURLConnection to add a header either. Please suggest how we could do this.
As mentioned above, this http request with the above header does work on curl and Postman without any errors - which tells me taht the request and authentication using the headers does work. However, the header is not getting set correctly using the above HttpUrlConnection class.
Thanks in advance!
Edit: I reviewed the link shared. The guy who asked the question probably had the same issue as me, but the solutions offered seem to be way different. Here, I am trying to authorize the user by using a custom header in the http request which is unique to the Rest API server I am talking to.
It is this custom header that I am unable to add. I have already tried most of the solutions suggested before posting here.
Note: wanted to reiterate - the above request works on curl and Postman. Postman has an option to generate the code required for the request, but for Java it only uses some library not the HttpURLConnection method.