发布Jira可在Python上运行,但不能在PowerShell上运行

时间:2019-09-30 09:05:43

标签: json powershell jira jira-rest-api

我正在尝试使用脚本向Jira发送POST请求,并且该请求在Python上运行良好,但在PowerShell中却无法正常运行。

我尝试使用PowerShell进行GET请求以从Jira获取一些数据,并且该请求有效,因此我认为登录详细信息是正确的。所以我唯一关心的是有效载荷。也许我的JSON格式不正确。

Python(有效):

headers = {
  "Accept": "application/json;charset=utf-8",
  "Content-Type": "application/json"
}

payload = {
  "fields": {
    "project": {
      "key": "SDF"
    },
    "summary": "test",
    "description": "Creating of an issue using project keys and issue type names using the REST API",
    "issuetype": {
      "name": "Request"
    }
  }
}

password = open('passwords_jira2snow.txt').readlines()
jira_login = HTTPBasicAuth(password[0].rstrip('\n'), password[1].rstrip('\n')) 

r = requests.post(url="domain/rest/api/2/issue", data = json.dumps(payload), auth=jira_login, verify=False, headers=headers)
#jira_response = json.loads(r.text)
print(r.text)

PowerShell(无效):

$payload = ('{
  "fields": {
    "project": {
      "key": "SDF"
    },
    "summary": "test",
    "description": "Creating of an issue using project keys and issue type names using the REST API",
    "issuetype": {
      "name": "Request"
    }
  }
}')
$hdrs1 = @{}
$hdrs1.Add("login",$login)
$hdrs1.Add("password",$password)

$CreateJira = Invoke-RestMethod -Method POST -Headers $hdrs1 -Uri "domain/rest/api/2/issue" -Body $payload -ContentType "application/json"
Write-Host $CreateJira

我要

ERROR: REST call to sessionauth endpoint failed with error 'ProtocolError -
System.Net.WebException: The remote server returned an error: (400) Bad Request.
     at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.GetResponse(WebRequest request)
     at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.ProcessRecord()'
Current endpoint: 'https://domain/sessionauth/v1/authenticate'

2 个答案:

答案 0 :(得分:1)

使用cmdlet get-help Invoke-RestMethod -Examples检查PS中的文档。有一个有关如何处理POST请求的示例。 不用在标题上设置凭据,而是创建凭据对象并使用-Credentials的{​​{1}}参数。

与REST上的POST请求相比,凭据的处理通常不同于GET请求。

另一方面,我建议您改用JiraPS Module,这样您就无需重新发明轮子,而不必专注于完成工作!

答案 1 :(得分:0)

不知道为什么,但是以其他方式定义凭据很有帮助。奇怪,因为默认情况下GET请求有效。

 $login = "test"
 $password = "test"  
 $pair = "$($login):$($password)"
 $encodedCreds = 
 [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))  
 $hdrs1.Add("Authorization", "Basic $encodedCreds")