RestSharp POST request translation from cURL request

牧云@^-^@ 提交于 2020-01-11 09:42:19

问题


I'm trying to make a POST request using RestSharp to create an issue in JIRA, and what I have to work with is an example that uses cURL. I'm not familiar with either enough to know what I'm doing wrong.

Here's the example given in cURL:

curl -D- -u fred:fred -X POST --data {see below} -H "Content-Type: application/json"
http://localhost:8090/rest/api/2/issue/

Here's their example data:

{"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"}}}

And here's what I'm attempting with 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);

What I get back is a 415 response of

Unsupported Media Type

Note: I also tried what was suggested in this post, but that did not resolve the issue. Any guidance is appreciated!


回答1:


dont do

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

instead try:

request.AddBody(issueToCreate);



回答2:


A clean and more reliable solution you could use is described below:

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);

The full code I uploaded to gist: https://gist.github.com/gandarez/50040e2f94813d81a15a4baefba6ad4d

Jira documentation: https://developer.atlassian.com/jiradev/jira-apis/jira-rest-apis/jira-rest-api-tutorials/jira-rest-api-example-create-issue



来源:https://stackoverflow.com/questions/13380845/restsharp-post-request-translation-from-curl-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!