Missed Team ’24? Catch up on announcements here.

×
Create
cancel
Showing results for 
Search instead for 
Did you mean: 
Sign up Log in

Using HttpClient (C#) to create a Jira Issue via REST generates Bad Request response

Will Burton August 21, 2012

Using C# with .Net 4.0 and Jira (5.1) REST service. Here's my attempt to create an issue:

string data = @"{""fields"":{""project"":{""key"": ""PROJECT_KEY""},""summary"": ""REST EXAMPLE"",""description"": ""Creating an issue via REST API"",""issuetype"": {""name"": ""Bug""}}}";
string postUrl = "https://localhost:8090/rest/api/latest/";

System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();

client.BaseAddress = new System.Uri(postUrl);
byte[] cred = UTF8Encoding.UTF8.GetBytes("username:password");
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(cred));
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

System.Net.Http.Formatting.MediaTypeFormatter jsonFormatter = new System.Net.Http.Formatting.JsonMediaTypeFormatter();

System.Net.Http.HttpContent content = new System.Net.Http.ObjectContent<string>(data, jsonFormatter);
System.Net.Http.HttpResponseMessage response = client.PostAsync("issue", content).Result;
if (response.IsSuccessStatusCode)
{
    string result = response.Content.ReadAsStringAsync().Result;
    descrptiontextBox.Text = result;
}
else
{
    descrptiontextBox.Text = response.StatusCode.ToString();
}

Here's my response:

Http 400 - BadRequest

Any Idea what I might be missing?

5 answers

Comments for this post are closed

Community moderators have prevented the ability to post new answers.

Post a new question

1 vote
Will Burton August 26, 2012

Got it to work by writing my own class I named Issue.

public class Issue
    {
        public Fields fields { get; set; }
        public Issue()
        {
            fields = new Fields();
        }
    }

    public class Fields
    {
        public Project project { get; set; }
        public string summary { get; set; }
        public string description { get; set; }
        public IssueType issuetype { get; set; }
        public Fields()
        {
            project = new Project();
            issuetype = new IssueType();
        }
    }

    public class Project
    {
        public string key { get; set; }
    }

    public class IssueType
    {
        public string name { get; set; }
    }

Then, I changed

System.Net.Http.HttpContent content = new System.Net.Http.ObjectContent<string>(data, jsonFormatter);

to

System.Net.Http.HttpContent content = new System.Net.Http.ObjectContent<Issue>(data, jsonFormatter);

Works now.

1 vote
Harry Chan
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
August 26, 2012

Hi, I believe the URL is incorrect. As per the REST example here, it should be <base ur>/rest/api/latest/issue/ and not <base url>/rest/api/latest/.

Will Burton August 26, 2012

Where are you seeing "test" ?

Harry Chan
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
August 26, 2012

Sorry, typo on my behalf. What I meant was that you are missing a issue/ at the end of the URL.

Will Burton August 26, 2012

Ha, then I suppose I have a misunderstanding of how PostAsync is supposed to work. I've seen it used to set the endpoint of the REST URL like here: http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client

Harry Chan
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
August 26, 2012

Sorry, not too familiar with C#, maybe someone else can add to this. Perhaps you need "issue/" instead of "issue" in post async?

0 votes
Sven [Dione Technology]
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
December 5, 2013

Hi,

I took your code but I have got another error :

using System;
using System.Collections.Generic;
using System.Json;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {

        static async void Run()
        {
            string data = @"{""fields"":{""project"":{""key"": ""TEST""},""summary"": ""REST EXAMPLE"",""description"": ""Creating an issue via REST API"",""issuetype"": {""name"": ""Bug""}}}";
            string postUrl = "http://localhost/rest/api/latest/issue/ ";

            System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();

            client.BaseAddress = new System.Uri(postUrl);
            byte[] cred = UTF8Encoding.UTF8.GetBytes("xxxx:xxxxx");
            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(cred));
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

            System.Net.Http.Formatting.MediaTypeFormatter jsonFormatter = new System.Net.Http.Formatting.JsonMediaTypeFormatter();

            System.Net.Http.HttpContent content = new System.Net.Http.ObjectContent&lt;string&gt;(data, jsonFormatter);
            System.Net.Http.HttpResponseMessage response = client.PostAsync("issue", content).Result;
            if (response.IsSuccessStatusCode)
            {
                String result = response.Content.ReadAsStringAsync().Result;
                Console.WriteLine(result);
            }
            else
            {
                Console.WriteLine(response.StatusCode.ToString());
            }
        }

        static void Main(string[] args)
        {
            Run();
            Console.WriteLine("Hit ENTER to exit...");
            Console.ReadLine();
        }
    }
}

I have a strange code error : MethodeNotAllowed

Could you please help me ?

0 votes
michal crkon
I'm New Here
I'm New Here
Those new to the Atlassian Community have posted less than three times. Give them a warm welcome!
April 4, 2013
Hi guys. I have the same problem with this line of code. I modified the code above for my purpose but I cant fix this error. I have tried everything. It looks like this line ignores my class Issue completelly. My knowledge in C# is still limited (in some cases i am confident and in some not but i like .net and c#)as I am a student only.
HttpContent content = new ObjectContent<Issue>(data, jsonFormatter);
can someone help me with this? Thanks a million, Michal
this is my first prototype
namespace _3_4_2013
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Net;
    using System.Net.Http;
    using System.Net.Http.Headers;   
    using System.Net.Http.Formatting;
   

    


    class Program
    {
        static void Main(string[] args)
        {
            

           
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("http://IP:Port/secure/CreateIssueDetails!init.jspa?pid=13839&issuetype=2&summary=New");
            byte[] cred = UTF8Encoding.UTF8.GetBytes("myusername:mypassword");
            
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",Convert.ToBase64String(cred));
                       
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            MediaTypeFormatter jsonFormatter = new JsonMediaTypeFormatter();
            string data = @"{""fields"":{""project"":{""key"": ""KP""},""summary"": ""REST EXAMPLE"",""description"":""Creating an issue via REST API"",""issuetype"": {""name"": ""Bug""},""mrNumber"": {""name"": ""AnyMrNumber what i will send later""}}}";


            //ObjectContent content = new HttpContent.(ApmData)(data, jsonFormatter);
            var product = new ApmData() { MainRequirementNumber = "Hi Miso" };
            Uri gizmoUri = null;//new Uri ("http://IP:Port/secure/CreateIssueDetails!init.jspa?pid=13839&issuetype=2&assignee=Michal&summary=New&reporter=EMICCRK");

            HttpResponseMessage response = client.PostAsJsonAsync("/secure/CreateIssueDetails!init.jspa?pid=13839&issuetype=1&summary=New&reporter=EKEICUN/", gizmoUri).Result;
            
            if (response.IsSuccessStatusCode)
            {
                string result = response.Content.ReadAsStringAsync().Result;
                gizmoUri = response.Headers.Location;
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }
            else
            {
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }                     
        }
        
    }
}
===========My class ApmData =====================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace _3_4_2013
{
    class ApmData
    {
        public string MainRequirementNumber { get; set; }
        public Fields fields { get; set; }
        public ApmData()
        {
            fields = new Fields();
        }
    }

    public class Fields
    {
        public Project project { get; set; }
        public string summary { get; set; }
        public string description { get; set; }
        public IssueType issuetype { get; set; }
        public string mrNumber { get; set; }
        public Fields()
        {
            project = new Project();
            issuetype = new IssueType();
            
        }
        

    }

    public class Project
    {
        public string key { get; set; }
    }
    public class IssueType
    {
        public string name { get; set; }
    }

}

=====================here is my second prototype=================

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Formatting;
   

namespace console_4_4_2013
{
    class Program
    {
        static void Main(string[] args)
        {
           

            string data = @"{""fields"":{""project"":{""key"": ""KP""},""summary"": ""REST EXAMPLE"",""description"":""Creating an issue via REST API"",""issuetype"": {""name"": ""Bug""},""mrNumber"": {""name"": ""AnyMrNumber what i will send later""}}}";
            string postUrl = "http://ip:port/rest/api/latest/";

            HttpClient client = new HttpClient();

            client.BaseAddress = new System.Uri(postUrl);

            byte[] cred = UTF8Encoding.UTF8.GetBytes("myusername:mypassword");
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(cred));

            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            MediaTypeFormatter jsonFormatter = new JsonMediaTypeFormatter();
            //System.Net.Http.HttpContent content = new System.Net.Http.ObjectContent<Issue>(data, jsonFormatter);
           HttpContent content = new ObjectContent<string>(data, jsonFormatter);
            HttpResponseMessage response = client.PostAsync("/secure/CreateIssueDetails!init.jspa?pid=13839&issuetype=1&summary=New&reporter=EKEICUN/", content).Result;
            if (response.IsSuccessStatusCode)
            {
                string result = response.Content.ReadAsStringAsync().Result;
                //descrptiontextBox.Text = result;
                //MrNumber = result;
                Console.WriteLine(result);
            }
            else
            {
                //descrptiontextBox.Text = response.StatusCode.ToString();
                //MrNumber = response.StatusCode.ToString();
                Console.WriteLine(response.StatusCode.ToString());
            }
        }
    }
}

I am getting response 200 OK in both prototypes but in the first one only when i use <string> instead of <Issue>

//System.Net.Http.HttpContent content = new System.Net.Http.ObjectContent<Issue>(data, jsonFormatter);

HttpContent content = new ObjectContent<string>(data, jsonFormatter);


Thanks for any help which helps me to understand better of this problem.



0 votes
Simon Meier
I'm New Here
I'm New Here
Those new to the Atlassian Community have posted less than three times. Give them a warm welcome!
December 19, 2012

How can you use a self-created type Issue in new System.Net.Http.ObjectContent<Issue>(data, jsonFormatter); ?

That doesn't work for me...

Comments for this post are closed

Community moderators have prevented the ability to post new answers.

Post a new question

TAGS
AUG Leaders

Atlassian Community Events