Selenium 4.3.0 GraphQL查询会话信息时JSON解析错误求助
解决Selenium 4.3.0 GraphQL会话查询的JSON解析错误
问题根源
错误提示Unable to determine type from: q明确指向请求体不符合JSON规范。Selenium Grid的GraphQL接口要求POST请求体必须是标准JSON格式,而你的curl命令中--data参数存在两个核心问题:
- JSON的键必须用双引号包裹,原请求中
query未加双引号,导致解析器无法识别合法的JSON结构 - GraphQL查询内容需要作为JSON字符串值存在,必须用双引号包裹,且内部的双引号需转义
修正后的Java代码
调整--data参数为合法JSON结构,同时处理字符串转义问题:
String graphqlQuery = "{ session (id: \"" + sessionId + "\") { id, capabilities, startTime, uri, nodeId, nodeUri, sessionDurationMillis, slot { id, stereotype, lastStarted } } }"; // 转义查询字符串中的双引号,确保符合JSON格式要求 String escapedQuery = graphqlQuery.replace("\"", "\\\""); String[] command = {"curl", "-X", "POST", "-H", "Content-Type: application/json", "--data", "{\"query\": \"" + escapedQuery + "\"}", "-s", "http://localhost:4444/graphql"}; ProcessBuilder process = new ProcessBuilder(command); try { Process p = process.start(); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); StringBuilder builder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { builder.append(line); builder.append(System.getProperty("line.separator")); } String result = builder.toString(); System.out.print(result); } catch (IOException e) { e.printStackTrace(); }
关键修正说明
- 给JSON键
query添加双引号:{"query": "..."},符合JSON语法规范 - 对GraphQL查询字符串中的双引号进行转义,避免破坏JSON结构
- 确保整个
--data参数是一个完整、可解析的JSON对象
终端验证方式
先在终端执行修正后的curl命令,确认能正常返回结果后再嵌入Java代码:
curl -X POST -H "Content-Type: application/json" --data "{\"query\": \"{ session (id: \\\"d5382daee94860671ae972fcba359e03\\\") { id, capabilities, startTime, uri, nodeId, nodeUri, sessionDurationMillis, slot { id, stereotype, lastStarted } } }\"}" -s http://localhost:4444/graphql
内容的提问来源于stack exchange,提问作者SacTan
相关产品推荐
相关产品推荐

