2012-11-14 351 views
3

我想使用RestSharp在JIRA中創建一個POST請求來創建問題,我必須使用的是使用cURL的示例。我不知道我做錯了什麼。從cURL請求翻譯RestSharp POST請求

下面是捲曲給出的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中提出的建議,但是這並沒有解決問題。任何指導表示讚賞!

回答

3

不做

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

,而不是嘗試:

request.AddBody(issueToCreate); 
+0

謝謝沃爾!對於任何發現這篇文章的人來說,因爲它特別與JIRA有關,我還發現Atlassian的REST服務(也許這是全面的)是區分大小寫的!在我的JiraIssue類中,我創建了諸如「Key」和「Summary」之類的屬性,但它必須是「key」和「summary」...... doh! – gopherr

+1

對於任何感興趣的人,我已經在JIRA REST客戶端和WPF應用程序[此處](https://bitbucket.org/grodgers/jiravu/overview)中實現了此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); 

完整的代碼我上傳到要點: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