0

我正在尝试使用 API 在 JIRA 中创建一个问题。如果我在 chrome 中使用邮递员,那么它工作正常。但是,如果我尝试使用 .net 代码来执行此操作,则会出现错误。

返回的错误是“400 错误请求”。

我在 StackOverflow 和 Web 上进行了与此相关的广泛搜索,但要么我找不到解决方案,要么给出的解决方案对我没有帮助。

这是我的一段代码:

        string data = @"{ ""fields"":{""project"":{""key"":""TES""},""summary"":""sum1"",""issuetype"":{""name"":""Bug""},""duedate"":""2013-01-24 09:00 AM +05:30"",""customfield_10000"":[{""value"":""None - Nothing""}],""reporter"":{""name"":""praveen_tadikemalla""}}}";


       //tried  by using new class Issue also
       /* Issue data = new Issue();
        data.fields = new Fields();
        data.fields.description = "test";
        data.fields.summary = "test bugs";

        data.fields.issuetype = new IssueType();
        data.fields.issuetype.name = "bug";

        data.fields.project = new Project();
        data.fields.project.key = "TES";         
       */

        string postUrl = "http://localhost:8080/rest/auth/latest/session";

        System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
        client.BaseAddress = new System.Uri(postUrl);


        byte[] cred = UTF8Encoding.UTF8.GetBytes("amit:GoMessiGo");

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

       //in case if i use custom Issue class   
       // System.Net.Http.HttpContent content = new System.Net.Http.ObjectContent<Issue>(data,jsonFormatter);


        System.Net.Http.HttpResponseMessage response = client.PostAsync("http://localhost:8080/rest/api/latest/issue/", content).Result;     

        string result=null;

        if (response.IsSuccessStatusCode)          
        {
            result = response.Content.ReadAsStringAsync().Result;
        }
        else
        {
           result  = response.StatusCode.ToString();
        }
      return result;

我已经在标题中发送了授权。

我可以点击 API 来获取请求。

我怀疑使用此方法向服务器发送发布请求时存在一些问题。(client.PostAsync)

   System.Net.Http.HttpResponseMessage response = client.PostAsync("http://localhost:8080/rest/api/latest/issue/", content).Result;    

或者

此代码段

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

但这些是我的假设

4

1 回答 1

0

我让它工作了。

我跟着这个链接。

通过 Rest c# httpClient 创建 jira 问题

我在我的项目中使用了这个 System.Net.Http.Formatting。并且此链接声明它仅适用于 Web 应用程序。

如果您在我的情况下创建任何其他类型的项目是控制台应用程序。我需要使用另一个 Json 反序列化类。或者我可以使用 StringContent 类。

所以使用 String Content 类解决了我的问题

于 2014-07-15T13:09:12.393 回答