RestSharp POST请求翻译自cURL请求

3
我正在尝试使用RestSharp进行POST请求,在JIRA中创建问题,我所拥有的是一个使用cURL的示例。我对两者都不熟悉,不知道哪里出了问题。
这是cURL中给出的示例
curl -D- -u fred:fred -X POST --data {see below} -H "Content-Type: application/json"
http://localhost:8090/rest/api/2/issue/

这里是他们的示例数据:
{"fields":{"project":{"key":"TEST"},"summary":"REST ye merry gentlemen.","description":"Creating of an issue using project keys and issue type names using the REST API","issuetype":{"name":"Bug"}}}

以下是我使用RestSharp尝试的内容:

RestClient client = new RestClient();
client.BaseUrl = "https://....";
client.Authenticator = new HttpBasicAuthenticator(username, password);
....// connection is good, I use it to get issues from JIRA
RestRequest request = new RestRequest("issue", Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddParameter("data", request.JsonSerializer.Serialize(issueToCreate));
request.RequestFormat = DataFormat.Json;
IRestResponse response = client.Execute(request);

我收到的是一个415响应。
Unsupported Media Type

注意:我也尝试了在此帖子中提到的方法,但这并没有解决问题。感谢任何指导!
2个回答

3

不要这样做

request.AddParameter("data", request.JsonSerializer.Serialize(issueToCreate));

可以尝试这样做:

request.AddBody(issueToCreate);

谢谢你,wal!对于其他因为与JIRA有关而发现这篇文章的人,我还发现Atlassian的REST服务(也许是全面的)是区分大小写的!在我的JiraIssue类中,我创建了像“Key”和“Summary”这样的属性,但它必须是“key”和“summary”...哎呀! - gopherr
1
对于任何感兴趣的人,我已经在一个 JIRA REST 客户端和 WPF 应用程序中实现了这个 RestSharp POST 这里 - gopherr

3
以下是一个更加干净、可靠的解决方案:

var client = new RestClient("http://{URL}/rest/api/2");
var request = new RestRequest("issue/", Method.POST);

client.Authenticator = new HttpBasicAuthenticator("user", "pass");

var issue = new Issue
{
    fields =
        new Fields
        {
            description = "Issue Description",
            summary = "Issue Summary",
            project = new Project { key = "KEY" }, 
            issuetype = new IssueType { name = "ISSUE_TYPE_NAME" }
        }
};

request.AddJsonBody(issue);

var res = client.Execute<Issue>(request);

if (res.StatusCode == HttpStatusCode.Created)
    Console.WriteLine("Issue: {0} successfully created", res.Data.key);
else
    Console.WriteLine(res.Content);

我已经上传了完整的代码到gist:https://gist.github.com/gandarez/50040e2f94813d81a15a4baefba6ad4d。Jira文档:https://developer.atlassian.com/jiradev/jira-apis/jira-rest-apis/jira-rest-api-tutorials/jira-rest-api-example-create-issue

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接