1

I'm trying to send a POST request via HttpClient, but server response says "unauthorized" error. How I can get the Bearer Token? I searched for solutions but I don't understand it..

That's my code and I don't know how I get the token for the request...

HttpPost request = new HttpPost("http://domain...");
request.setHeader(HttpHeaders.ACCEPT, "application/json, text/plain, */*");
request.setHeader(HttpHeaders.CONTENT_TYPE, "application/#json");
request.setHeader(HttpHeaders.ACCEPT_LANGUAGE, "de,en-US;q=0.7,en;q=0.3");
request.setHeader(HttpHeaders.ACCEPT_ENCODING, "gzip, deflate, br");
request.setHeader(HttpHeaders.REFERER, "https://domain...");
request.setHeader("DNT", "1");
request.setHeader(HttpHeaders.HOST, "host..");
String authToken = ""; // ... ?
request.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + authToken);
StringEntity params = new StringEntity("{}");
params.setContentEncoding("UTF-8");
request.setEntity(params);
response = this.getHttpClient().execute(request);
Kartik
  • 7,677
  • 4
  • 28
  • 50
Daniela Grave
  • 11
  • 1
  • 1
  • 2

2 Answers2

0

First you have to authenticate user using user name and password(Using HTTP call) then you will have token in response same you can add it to your next POST call in header.

One get/post call is required before your POST call so that you will have token. Same token can be used for all further call.

0

Seems you are trying to access some APIs which requires you to first get some access token (bearer token) before to hitting actual API.

Most flows involve two steps as explained below.

Step 1. Fetch bearer token with basic authentication (below endpoint and parameter are sample value and will be different for your API)

POST /auth 
`request.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + authToken);`

Step 2: Step1 will give you some kind of access token in response. You need to use that to make any subsequent API call.

GET /Student/Mark
`request.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + authToken);`

You can read more about bearer token at What is the OAuth 2.0 Bearer Token exactly?

Let me know in case you still have any doubts or not able to access your API with the approach I mentioned.