来自cURL请求的RestSharp POST请求转换

时间:2012-11-14 14:35:09

标签: c# .net curl jira restsharp

我正在尝试使用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中的建议,但是没有解决问题。任何指导表示赞赏!

2 个答案:

答案 0 :(得分:3)

不要做

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

而不是尝试:

request.AddBody(issueToCreate);

答案 1 :(得分: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