Search code examples
javaspringjerseyjax-rsjersey-client

Calling API again if it returns Http 401


I am calling below API using jersey

JsonObject response = ConnectionUtil.getwebTarget()
                                        .request().
                 header("Authorization", "Bearer "+ access_token)
                                        .get(JsonObject.class);

Here accessToken is variable which got value by calling another API. Now if response.getStatus() returnd 401 I want to call the API to get token and will call the above commnad again. how can I stop myself from duplication? As of now I am writing below code.

JsonObject response = ConnectionUtil.getwebTarget()
                                            .request().
                     header("Authorization", "Bearer "+ access_token)
                                            .get(JsonObject.class);
  if(response.getStatus()==401)
  {
    accessToken= new AccessToken().getAccessToken();
    JsonObject response = ConnectionUtil.getwebTarget()
                                            .request()
                                            .header("Authorization", "Bearer "+ access_token)
                                            .get(JsonObject.class);
}

how can I reduce writing the code of line JsonObject response twice. I atleast want to check twice 401 code before throwing customized exception

I am new to java programming. can somebody tell me logic. its basic coding but I am still struggling.


Solution

  • Write a subroutine.

    private JsonObject doRequest(AccessToken access_token) {
        return ConnectionUtil.getwebTarget()
                 .request()
                 .header("Authorization", "Bearer "+ access_token)
                 .get(JsonObject.class);
    }
    

    and then use it twice

    JsonObject response = doRequest(access_token);
    if (response.getStatus() == 401) {
        access_token = new AccessToken().getAccessToken();
        response = doRequest(access_token);
    }
    

    'doRequest' might not be the best name to choose, but I don't know what the big picture is - i.e., what is it actually doing?