【问题标题】:RestSharp POST request translation from cURL request来自 cURL 请求的 RestSharp POST 请求翻译
【发布时间】:2012-11-14 14:35:09
【问题描述】:

我正在尝试使用 RestSharp 发出 POST 请求以在 JIRA 中创建问题,而我必须使用的是使用 cURL 的示例。我对任何一个都不够熟悉,无法知道我做错了什么。

这是 cURL 中给出的example

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

注意:我也尝试了this post 中的建议,但这并没有解决问题。任何指导表示赞赏!

【问题讨论】:

    标签: c# .net curl jira restsharp


    【解决方案1】:

    别这样

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

    改为尝试:

    request.AddBody(issueToCreate);
    

    【讨论】:

    • 谢谢你,沃尔!对于发现这篇文章的任何其他人,因为它与 JIRA 相关,我还发现 Atlassian 的 REST 服务(也许这是全面的)区分大小写!在我的 JiraIssue 类中,我正在创建像“Key”和“Summary”这样的属性,但它必须是“key”和“summary”......doh!
    • 对于任何感兴趣的人,我已经在 J​​IRA REST 客户端和 WPF 应用程序here 中实现了这个 RestSharp POST。
    【解决方案2】:

    您可以使用的干净且更可靠的解决方案如下所述:

    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

    【讨论】:

      猜你喜欢
      • 2017-11-28
      • 1970-01-01
      • 1970-01-01
      • 2015-05-13
      • 1970-01-01
      • 2016-10-17
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多