How to get Selenium Node IP for reference?

How to get Selenium Node IP for reference?
Photo by Mailchimp / Unsplash

To get the nodeUri of a Selenium node in Java using GraphQL, you can use the Apache HttpClient library to send a POST request to the Selenium Grid hub's GraphQL endpoint, and then parse the response to extract the nodeUri.

Here's an example code snippet that demonstrates how to do this:

try (CloseableHttpClient client = HttpClients.createDefault()) {
                HttpPost httpPost = new HttpPost(hubIp + "/graphql");
                String query = "{\n" +
                        "    \"query\": \"{session (id: \\\"" + sessionId + "\\\") { id, capabilities, startTime, uri, nodeId, nodeUri, sessionDurationMillis, slot { id, stereotype, lastStarted } } }\"\n" +
                        "}";
                StringEntity entity = new StringEntity(query);
                httpPost.setEntity(entity);
                httpPost.setHeader("Accept", "application/json");
                CloseableHttpResponse response = client.execute(httpPost);
                HttpEntity responseEntity = response.getEntity();
                String responseString = EntityUtils.toString(responseEntity);
                JsonObject jsonObject = new JsonParser().parse(responseString).getAsJsonObject();
                ipAddress = jsonObject.getAsJsonObject("data").getAsJsonObject("session").get("nodeUri").getAsString();

            } catch (Exception e) {
                logger.error("Unable to get Selenium node IP address: " + e.getMessage());
            }

WIth below import

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;