How to use JSON Web Token (JWT) in java for each request?

I already have the JWT token and URL given like below:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

URL :

I want to use the JWT token with the above URL for a subsequent request, in Java to get the corresponding response.

1

2 Answers

This is the rough example for it (Assuming you're using OkHttpClient)

OkHttpClient client = new OkHttpClient(); MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded"); RequestBody body = RequestBody.create(mediaType, "message=somemessage"); Request request = new Request.Builder() .url("") .post(body) .addHeader("Content-Type", "application/x-www-form-urlencoded") .addHeader("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c,Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c") .addHeader("cache-control", "no-cache") .build(); Response response = client.newCall(request).execute(); 

However it really depends on the web implementation

I wish you have provided few more details so that I could suggest an exact implementation.
You have to add JWT in request header to get response in all the subsequent requests. Once you get the JWT you can store it in session and use it in all following requests. I am using rest template, you can follow the same in your client

 String url =""; HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(new MediaType[]{MediaType.APPLICATION_JSON})); headers.set("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKK"); HttpEntity<String> httpEntity = new HttpEntity<>(requestBody,headers); ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class); 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like