首页 > 解决方案 > 如何正确格式化我的 URl 以使用图形 APi 过滤器

问题描述

我有以下在 POSTMAN 中按预期工作的 Url 图 APi:

https://graph.microsoft.com/v1.0/users ?$filter=mail eq 'myuser@hotmail.com'

当我使用 groovy 脚本将 URl 传递给图形 API 时,出现以下错误:

java.net.URISyntaxException:索引 52 处查询中的非法字符:https : //graph.microsoft.com/v1.0/users/ ?$filter=mail eq 'myuser@gmail.com'

这是我如何构建 URl 的示例代码:

 String _url =graph_base_user_url + '?\$filter=mail eq ' + "'" + userEmail + "'"

 def http = new HTTPBuilder(java.net.URLEncoder.encode(_url, "UTF-8"))

=====> 更新 ======= 我已经对我的方法应用了以下更改,我没有任何错误,但奇怪的是返回 json 内容所有我的用户而不是单个记录。下面是我的方法

Thnaks for your reply,

我有一个奇怪的问题,当我在 POSTMAN 中尝试过滤器时,它会根据提供的电子邮件返回正确的记录

但是当我在 groovy 脚本中使用它时,它会返回我的所有用户而不是过滤器记录,

这是我的方法如下:

public String getUserIdByEmailQuery(String AuthToken,String userEmail){

     String _ret

         def http = new HTTPBuilder(graph_base_user_url +"?")
         http.request(GET) {

             requestContentType = ContentType.JSON
             query:[ $filter:"mail eq '$userEmail'" ]

             headers.'Authorization' = "Bearer " + AuthToken    

             response.success = { resp, json ->
                 //_userId=json["id"].toString()
                 _ret=json
             }

             // user ID not found : error 404
             response.'404' = { resp ->       
                 _ret = 'Not Found'
             }

         }
         _ret
     } 

我的方法参数 graph_base_user_url 等于“ https://graph.microsoft.com/v1.0/users

知道为什么它返回所有用户而不是过滤记录吗?请注意,我已经交叉检查了参数中的用户邮件,它是正确的并且存在

感谢您的帮助问候

标签: groovyazure-active-directory

解决方案


您应该以惯用的方式使用 HTTPBuilder:

def http = new HTTPBuilder( graph_base_user_url )
def result = http.get( query:[ $filter:"mail eq '$userEmail'" ] )

更新:

您的代码未正确传递查询参数。它应该是:

        def http = new HTTPBuilder(graph_base_user_url)
         http.request(GET) {
             ...
             uri.query = [ $filter:"mail eq '$userEmail'", $select:id ] 
             ...
        }

推荐阅读