Template Design for Using Auth Tokens

I am a client-side developer, moving to server development. One of the common problems that I am facing is the need to make one API call (say, to get an authentication token), and then make a subsequent API call to get the data I want. Sometimes I need to make two API calls for data, without an authentication token.

Is there a common design pattern or Java library to solve this problem? Or do I need to manually create a call chain every time I need it?

Edit: I hope for something similar to this

CustomClassBasedOnJson myStuff = callAPI("url", getResponse("authURL"));

This will call "url" with data retrieved from "authURL". The thing is, I am building several URLs using the result of one call to determine the next.

+4
source share
1 answer

When doing server-side programming, it is acceptable that HTTP calls are invoked synchronously.

Therefore, the correct template is to simply make the first call, get the result, and then use it on the next line. There is no need to separate calls into separate threads or asynchronous calls if there isn’t much processing between the HTTP calls.

For instance:

 JsonResponseEntry getJsonReportResponse() throws IOException {
         String sReportURL = "https://someurl.com/v2/report/report?" +
                 "startts=" + getDateYesterday("ts") +
                 "&endts=" + getDateNow("ts") +
                 "&auth=" + getAuthCode();

         URL reportURL = new URL(sReportURL);
         URLConnection conn = reportURL.openConnection();
         BufferedReader buf = new BufferedReader(new InputStreamReader(conn.getInputStream()));
         ObjectMapper mapper = new ObjectMapper();
        JsonNode reportResult = mapper.readTree(buf);
         return convertJSonNodeToJsonResponseEntry(reportResult);
    }

    String getAuthCode() throws IOException {
        String sReportURL = "https://someurl.com/auth";
        URL reportURL = new URL(sReportURL);

        HttpURLConnection conn = (HttpURLConnection) reportURL.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.connect();

        String urlParameters = "username=myUserName&password=mypassword";
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();
        BufferedReader buf = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        ObjectMapper mapper = new ObjectMapper();
        AuthResponse response = mapper.readValue(buf, AuthResponse.class);
        return response.toString();
    }

The getAuthCode () function is synchronously called inside a URL that requires a response.

+1
source

Source: https://habr.com/ru/post/1530837/


All Articles