'Call RestApi endpoint resource from EJB

I have been looking around for sample code how to call a Restful service written in Spring boot (deployed in different server/ip) from an EJB client.

I couldn't find a simple example or reference to guide me on how to implement an EJB client that can call a restful service(deployed in different server/ip). Could you please point me to a document or example that shows or describe how the two can interface/talk to each other.

I need to call the endpoint by passing two header parameters for authentication, if authentication is success then only retrieve the details from Rest and send back the response to EJB client.



Solution 1:[1]

I use something like this, try

`public void calExternal() throws ProtocolException,
        MalformedURLException,
        IOException,
        NoSuchAlgorithmException,
        InvalidKeyException {
    URL myurl = new URL("API END POINT URL");
        ObjectMapper mapper = new ObjectMapper();
    HttpURLConnection conn = (HttpURLConnection) myurl.openConnection();
    conn.setUseCaches(false);
    conn.setDoInput(true);
    conn.setDoOutput(true);
    String payLoad = mapper.writeValueAsString("your payload here");

    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json");
    conn.setRequestProperty("AUTHORIZATION-TYPE", "HMAC");
    try {
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(payLoad);
        wr.flush();

        InputStream in = null;
        int responseCode = conn.getResponseCode();
        if (responseCode == 200) {
            in = conn.getInputStream();
        } else {
            in = conn.getErrorStream();
         
        }
        String encoding = conn.getContentEncoding() == null ? "UTF-8" : conn.getContentEncoding();
        String response = IOUtils.toString(in, encoding);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Asgar