azure - AZ REST DevOps 方法返回 "az : Not a json response"

标签 azure azure-powershell azure-cli2

我在 Windows 10 计算机上运行 powershell 运行 AZ REST 方法时出现问题。该脚本可以工作,甚至可以与用户帐户一起使用,但现在失败了,我不知道为什么。这是进行 AZ REST 调用的核心函数。

function getreleasedefinitionrequest($definitionid, $org, $project)
{
    $requestpath = "/_apis/release/definitions/" + $definitionid + "?api-version=6.0-preview.4"
    $tokeninfo = az account get-access-token | convertfrom-json
    $token = $tokeninfo.accessToken
    $uribase = "https://vsrm.dev.azure.com/" + $org + "/" + $project
    $uri = $uribase+$requestpath
    $authheader = "Authorization=Bearer " + $token
    $result = az rest --uri $uri --headers $authheader | convertfrom-json
    return $result
}

为了确保我使用的帐户具有权限,我明确注销然后重新登录,如图所示

Az logout –username ‘emailusername’
Clear-AzContext
Connect-AzAccount 
az login --only-show-errors --allow-no-subscriptions 

运行脚本的 AZ REST 行会产生错误

> az : Not a json response, outputting to stdout. For binary data
> suggest use "--output-file" to write to a file At line:1 char:1
> + az rest --uri $uri --headers $authheader
> + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
>     + CategoryInfo          : NotSpecified: (Not a json resp...write to a file:String) [], RemoteException
>     + FullyQualifiedErrorId : NativeCommandError   The command failed with an unexpected error. Here is the traceback: 'charmap' codec can't
> encode character '\u221e' in position 6302: character maps to
> <undefined> Traceback (most recent call last):   File
> "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure\cli\command_modules\util\custom.py",
> line 18, in rest_call   File
> "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-yh2ypeu1\requests\requests\models.py",
> line 897, in json   File "C:\Program Files (x86)\Microsoft
> SDKs\Azure\CLI2\lib\json\__init__.py", line 354, in loads
>     return _default_decoder.decode(s)   File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\json\decoder.py", line 339, in
> decode
>     obj, end = self.raw_decode(s, idx=_w(s, 0).end())   File "C:\Program Files (x86)\Microsoft
> SDKs\Azure\CLI2\lib\json\decoder.py", line 357, in raw_decode
>     raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 3 column 1 (char
> 4).....

将输出设置为文件无助于解决此问题。输出也包含在下面。

您认为这次通话出了什么问题吗?

--来自调试输出的有趣片段(组织和项目名称已更改以保护无辜者)

PS C:\> az rest --uri $uri --headers $authheader --debug
az : Command arguments: ['rest', '--uri', 'https://vsrm.dev.azure.com/bugs/bunny/_apis/release/definitions/25?api-version=6.0-preview.4', '--headers', 
'Authorization=Bearer {a valid token here}, '--debug']
At line:1 char:1
+ az rest --uri $uri --headers $authheader --debug
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (Command argumen...Bg', '--debug']:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError
 

Found a match in the command table for 'rest'
Event: CommandInvoker.OnPreCommandTableTruncate [<function AzCliLogging.init_command_file_logging at 0x0432B978>]
...
Request method: 'GET'
Request headers:
    'User-Agent': 'AZURECLI/2.9.1 (MSI)'
    'Accept-Encoding': 'gzip, deflate'
    'Accept': '*/*'
    'Connection': 'keep-alive'
    'Authorization': 'Bearer eyJ0eXAiOiJKV...'
    'x-ms-client-request-id': '28123a14-8d60-4263-95a6-b7634ad14fae'
    'CommandName': 'rest'
    'ParameterSetName': '--uri --headers --debug'
Request body:
None
urllib3.connectionpool : Starting new HTTPS connection (1): vsrm.dev.azure.com:443
urllib3.connectionpool : https://vsrm.dev.azure.com:443 "GET /bugs/bunny/_apis/release/definitions/25?api-version=6.0-preview.4 HTTP/1.1" 302 638
urllib3.connectionpool : Starting new HTTPS connection (1): spsprodeus24.vssps.visualstudio.com:443
urllib3.connectionpool : https://spsprodeus24.vssps.visualstudio.com:443 "GET /_signin?realm=vsrm.dev.azure.com&reply_to=https%3A%2F%2Fvsrm.dev.azure.com%2Fbugs%2Fbunny%2F_apis%2Frelease%2Fdefinitions%2F25%3Fapi-version%3D6.0-preview.4&redirect=1&hid=6f3eb511-31e9-4467-8450-015b9e4c36d7&force=1&context=eyJodCI6MiwiaGlkIjoiNWN
lYzEyNTYtYzgyNi00YmYwLWEzN2YtMDMzY2RlZDZjOTdkIiwicXMiOnt9LCJyciI6IiIsInZoIjoiIiwiY3YiOiIiLCJjcyI6IiJ90 HTTP/1.1" 203 15761
Response status: 203
Response headers:
    'Cache-Control': 'no-cache, no-store, must-revalidate'
    'Pragma': 'no-cache'
    'Content-Length': '15761'
    'Content-Type': 'text/html; charset=utf-8'
    'Expires': '-1'
    'P3P': 'CP="CAO DSP COR ADMa DEV CONo TELo CUR PSA PSD TAI IVDo OUR SAMi BUS DEM NAV STA UNI COM INT PHY ONL FIN PUR LOC CNT"'
 ....
Response content:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    
    
<html lang="en-US">
<head><title>
    
            Azure DevOps Services | Sign In
        
</title><meta http-equiv="X-UA-Compatible" content="IE=11;&#32;IE=10;&#32;IE=9;&#32;IE=8" />
    <link rel="SHORTCUT ICON" href="/favicon.ico"/>
    <link data-bundlelength="508967" data-bundlename="commoncss" 
data-highcontrast="/_static/tfs/M175_20200921.1/_cssbundles/HighContrast/vss-bundle-commoncss-vbprQZmxiRGQT6OOu7QI7gB_rewyS40Ce_ulm1Fh3rQQ=" 
data-includedstyles="jQueryUI-Modified;Core;Splitter;PivotView" 
href="/_static/tfs/M175_20200921.1/_cssbundles/Default/vss-bundle-commoncss-v18eOGnLpZpVm7mtRF63HJdB9wzrq2LZpAxko9qNRfdY=" rel="stylesheet" />
<link data-bundlelength="116298" data-bundlename="viewcss" 
data-highcontrast="/_static/tfs/M175_20200921.1/_cssbundles/HighContrast/vss-bundle-viewcss-vEVbIBXjzIJjwNr9KLU5WDHxT9Mx0Vzbs0OoptSmlcL0=" 
data-includedstyles="VSS.Controls" href="/_static/tfs/M175_20200921.1/_cssbundles/Default/vss-bundle-viewcss-vy_tKROQBdqLPOEEYAX4_J3xujP2C8V_PKfv97xulJp4=" rel="stylesheet" 
/>
    <!--UxServices customizations -->
    
    <link href="/_static/tfs/M175_20200921.1/_content/Authentication.css" type="text/css" rel="stylesheet" />
    
</head>
<body class="platform">
    <script type="text/javascript"> var __vssPageContext = 
....

<script type="text/javascript">if (window.performance && window.performance.mark) { window.performance.mark('endLoadBundleOuter-basejs'); }</script>
<script type="text/javascript"> require.config(__vssPageContext.moduleLoaderConfig);</script>
    <input name="__RequestVerificationToken" type="hidden" value="VBtc64BwCvt771roAgRwaemm_A9O3oDLlv1IBcNtee3hQFIK_0JwwQKAPDld6FUF3yuOOQPu98NQHsnD6ClR8SM5cs81" /><input 
name="__RequestVerificationToken2" type="hidden" value="__RequestVerificationToken29e00bc5d-8f47-40f7-a563-08eba0d0aeff" />
    
    
    
    
    <div class="account signin main-container hide">
            <div class="page-content">
                <div class="header-section" role="banner">
                    
                    <link rel="stylesheet" type="text/css" href="/_static/tfs/M175_20200921.1/_content/Combined.css">
                    <div id="ux-header" class="FF ltr vsIntegrate" xmlns="http://www.w3.org/1999/xhtml">
                        <span id="isMobile"></span>
                        <div class="upperBand">
                            <div class="upperBandContent">
                                <div class="left"></div>
                                <div class="right">
                                    <div class="profileImage"></div>
                                    <div id="signIn">
                                        <a class=":SignedOutProfileElement: createProfileLink" href="/go/profile" title="Anonymous">Anonymous</a>
                                        <a class="scarabLink" href="/_signout">Sign out</a>
                                    </div>
                                </div>
                                <div class="clear-both"></div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="content-section" role="main">
                    
    
            <div class="signin-main-content">
                <noscript>
                    <span class="error">Microsoft Internet Explorer&#39;s Enhanced Security Configuration is currently enabled on your environment. This enhanced level of 
security prevents our web integration experiences from displaying or performing correctly. To continue with your operation please disable this configuration or contact your 
administrator.</span>
                </noscript>
                <div class="provider-control">                    
                    <script class="options" defer="defer" type="application/json">{"providerOptions":{"force":true,"orgIdAuthUrl":"https://login.microsoftonline.com/6c637512
-c417-4e78-9d62-b61258e4b619/oauth2/authorize?client_id=499b84ac-1321-427f-aa17-267ca6975798\u0026site_id=501454\u0026response_mode=form_post\u0026response_type=code+id_toke
n\u0026redirect_uri=https%3A%2F%2Fspsprodeus24.vssps.visualstudio.com%2F_signedin\u0026nonce=864655b9-45b2-4b3a-b583-bb1283556687\u0026state=realm%3Dvsrm.dev.azure.com%26rep
ly_to%3Dhttps%253A%252F%252Fvsrm.dev.azure.com%252Fbugs%252Fbunny%252F_apis%252Frelease%252Fdefinitions%252F25%253Fapi-version%253D6.0-preview.4%26ht%3D2%
26hid%3D6f3eb511-31e9-4467-8450-015b9e4c36d7%26force%3D1%26nonce%3D864655b9-45b2-4b3a-b583-bb1283556687\u0026resource=https%3A%2F%2Fmanagement.core.windows.net%2F\u0026cid=8
64655b9-45b2-4b3a-b583-bb1283556687\u0026wsucxt=1\u0026prompt=select_account","user":null,"signInContext":"eyJodCI6MiwiaGlkIjoiNWNlYzEyNTYtYzgyNi00YmYwLWEzN2YtMDMzY2RlZDZjOT
dkIiwicXMiOnsicmVhbG0iOiJ2c3JtLmRldi5henVyZS5jb20iLCJyZXBseV90byI6Imh0dHBzOi8vdnNybS5kZXYuYXp1cmUuY29tL3JlZG1ldGFsL2Nvbm5lY3RlZGNvbW11bml0aWVzL19hcGlzL3JlbGVhc2UvZGVmaW5pdGl
vbnMvMjU_YXBpLXZlcnNpb249Ni4wLXByZXZpZXcuNCIsImh0IjoiMiIsImhpZCI6IjZmM2ViNTExLTMxZTktNDQ2Ny04NDUwLTAxNWI5ZTRjMzZkNyIsImZvcmNlIjoiMSIsIm5vbmNlIjoiODY0NjU1YjktNDViMi00YjNhLWI1
ODMtYmIxMjgzNTU2Njg3In0sInJyIjoiIiwidmgiOiIiLCJjdiI6IiIsImNzIjoiIn01"}}</script>
                </div>
            </div>
                </div>
                 
    
    </div>
    
    
  ...
</body>
</html>
Not a json response, outputting to stdout. For binary data suggest use "--output-file" to write to a file
cli.azure.cli.core.util : The command failed with an unexpected error. Here is the traceback:
The command failed with an unexpected error. Here is the traceback:
cli.azure.cli.core.util : 'charmap' codec can't encode character '\u221e' in position 6302: character maps to <undefined>
Traceback (most recent call last):
  File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure\cli\command_modules\util\custom.py", line 18, in rest_call
  File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-yh2ypeu1\requests\requests\models.py", line 897, in json
  File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\json\__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\json\decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\json\decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 3 column 1 (char 4)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-yh2ypeu1\knack\knack\cli.py", line 215, in invoke
  File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure\cli\core\commands\__init__.py", line 654, in execute
  File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure\cli\core\commands\__init__.py", line 718, in _run_jobs_serially
  File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure\cli\core\commands\__init__.py", line 711, in _run_job
  File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-yh2ypeu1\six\six.py", line 703, in reraise
  File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure\cli\core\commands\__init__.py", line 688, in _run_job
  File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure\cli\core\commands\__init__.py", line 325, in __call__
  File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure\cli\core\__init__.py", line 776, in default_command_handler
  File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure\cli\command_modules\util\custom.py", line 22, in rest_call
  File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-yh2ypeu1\colorama\colorama\ansitowin32.py", line 41, in write
  File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-yh2ypeu1\colorama\colorama\ansitowin32.py", line 162, in write
  File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-yh2ypeu1\colorama\colorama\ansitowin32.py", line 190, in write_and_convert
  File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-yh2ypeu1\colorama\colorama\ansitowin32.py", line 195, in write_plain_text
  File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u221e' in position 6302: character maps to <undefined>
'charmap' codec can't encode character '\u221e' in position 6302: character maps to <undefined>
Traceback (most recent call last):
  File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure\cli\command_modules\util\custom.py", line 18, in rest_call
  File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-yh2ypeu1\requests\requests\models.py", line 897, in json
  File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\json\__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\json\decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\json\decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 3 column 1 (char 4)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-yh2ypeu1\knack\knack\cli.py", line 215, in invoke
  File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure\cli\core\commands\__init__.py", line 654, in execute
  File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure\cli\core\commands\__init__.py", line 718, in _run_jobs_serially
  File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure\cli\core\commands\__init__.py", line 711, in _run_job
  File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-yh2ypeu1\six\six.py", line 703, in reraise
  File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure\cli\core\commands\__init__.py", line 688, in _run_job
  File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure\cli\core\commands\__init__.py", line 325, in __call__
  File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure\cli\core\__init__.py", line 776, in default_command_handler
  File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure\cli\command_modules\util\custom.py", line 22, in rest_call
  File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-yh2ypeu1\colorama\colorama\ansitowin32.py", line 41, in write
  File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-yh2ypeu1\colorama\colorama\ansitowin32.py", line 162, in write
  File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-yh2ypeu1\colorama\colorama\ansitowin32.py", line 190, in write_and_convert
  File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-yh2ypeu1\colorama\colorama\ansitowin32.py", line 195, in write_plain_text
  File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u221e' in position 6302: character maps to <undefined>
{truncated end of file}

最佳答案

根据错误,您没有提供正确的访问 token 。因为 Azure CLI az account get-access-token 只能获取访问 token 来获取 Azure 资源或 Azure AD 资源。它不能用于获取 Azure DevOps 访问 token 。更多详情请引用herehere .

如果您想使用 CLI 来管理 Azure DevOps,可以使用 Azure DevOps CLI 。例如,如果要获取发布定义,可以使用命令 az pipelines release definition show .

<小时/>

更新

如果您想使用PAT调用Azure Devops Rest API,请引用以下脚本

$username =""
$password="<your PAT>"
$tokens = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username,$password)))


$authheader = "Authorization=Basic " + $tokens 
$res = az rest --uri "https://vsrm.dev.azure.com/jim0375/test/_apis/release/definitions?api-version=6.0" --headers  $authheader 
$res

enter image description here

关于azure - AZ REST DevOps 方法返回 "az : Not a json response",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64434538/

相关文章:

仅当注册未登录时才使用短信的 Azure b2c mfa

azure - 获取容器内子目录中的所有 blob

python - 语法无效 : Azure CLI with Python

用于从 Azure DevOps 创建应用程序注册的 Azure CLI - 权限不足

Azure 交互式 shell 历史记录

c# - DocumentDB 分页与排序

azure - 计算机视觉 2.0 PDF 到文本不起作用

azure - 仅允许azure服务调用azure逻辑应用程序?

azure - 删除 vmss 网络接口(interface)配置时出错

azure - 在 azure 自动化上执行 Invoke-AzureRmVMRunCommand 时出现问题