如何解决AZ REST DevOps方法返回“ az:不是json响应”
我正在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; IE=10; IE=9; 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'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",in loads
return _default_decoder.decode(s)
File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\json\decoder.py",in decode
obj,0).end())
File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\json\decoder.py",in raw_decode
raise JSONDecodeError("Expecting value",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,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",encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u221e' in position 6302: character maps to <undefined>
{truncated end of file}
解决方法
根据错误,您没有提供正确的访问令牌。因为Azure CLI az account get-access-token
只能获取访问令牌才能获取Azure资源或Azure AD资源。它不能用于获取Azure DevOps访问令牌。有关更多详细信息,请参阅here和here。
如果要使用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 " + $base64AuthInfo
$res = az rest --uri "https://vsrm.dev.azure.com/jim0375/test/_apis/release/definitions?api-version=6.0" --headers $authheader
$res
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。