You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PowerShell调用Azure DevOps API的POST请求中传递非英文字符

解决方案

这个报错的核心原因是PowerShell默认发送JSON请求时未使用UTF-8编码,导致Azure DevOps API无法正确识别包含非英文字符的请求体。可按以下步骤修复:

适配所有PowerShell版本的通用方案

将JSON请求体显式转为UTF-8编码的字节数组后再发送,示例代码如下:

# 构造Patch请求体结构
$patchDocument = @(
    @{
        op = "add"
        path = "/fields/System.Title"
        value = "包含中文/日文等非英文字符的内容"
    }
)

# 转换为JSON字符串
$jsonBody = $patchDocument | ConvertTo-Json -Depth 10

# 显式转为UTF-8编码的字节数组
$utf8EncodedBody = [System.Text.Encoding]::UTF8.GetBytes($jsonBody)

# 调用Azure DevOps API
Invoke-RestMethod `
    -Uri "https://dev.azure.com/{组织名}/{项目名}/_apis/wit/workitems/${工作项类型}?api-version=7.0" `
    -Method Post `
    -Headers @{
        Authorization = "Basic " + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":你的个人访问令牌(PAT)"))
    } `
    -Body $utf8EncodedBody `
    -ContentType "application/json-patch+json; charset=utf-8"

PowerShell 7+ 简化方案

PowerShell 7及以上版本可直接通过ConvertTo-Json的编码参数生成符合要求的请求体:

$patchDocument = @(
    @{
        op = "add"
        path = "/fields/System.Title"
        value = "包含非英文字符的内容"
    }
) | ConvertTo-Json -Depth 10 -AsByteStream -Encoding UTF8

Invoke-RestMethod `
    -Uri "你的Azure DevOps API地址" `
    -Method Post `
    -Headers $headers `
    -Body $patchDocument `
    -ContentType "application/json-patch+json; charset=utf-8"

注意事项

  • 必须在ContentType参数值末尾追加charset=utf-8声明,确保服务端按UTF-8规则解析请求体
  • PowerShell 5.1版本默认会将字符串类型的Body以UTF-16编码发送,和Azure DevOps API预期编码不匹配,因此必须转为字节数组
  • 若请求体为多层嵌套结构,需为ConvertTo-Json指定足够大的-Depth参数值,避免JSON被截断

内容的提问来源于stack exchange,提问作者Anthony Hunter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 13:18:04