运行代码时收到C#(400)错误请求响应,而URL在Web浏览器上运行良好

时间:2017-09-14 21:07:23

标签: c# rest jira httpwebresponse jira-rest-api

我正在尝试通过C#代码从Jira检索查询的内容。我的网址为 http://jira-server/issues/rest/api/2/search?jql=filter=67355 。当我在任何Web浏览器中粘贴此URL时,我以JSON格式获取所有内容,而当我从代码执行它时,我得到以下异常

System.Net.WebException:'远程服务器返回错误:(400)错误请求。

奇怪的是 http://jira-server/issues/rest/api/2/search?filter=67355 。在Web浏览器和代码上以类似的方式工作,但输出不是我所期望的。

这是我的代码

public class Jira_To_Excel
{
    private const string exec_URL = "http://<jira-server>/issues/rest/api/2/search?filter=67355";
    private string Username;
    private string Password;

    public Jira_To_Excel(string username, string password)
    {
        Username = username;
        Password = password;
    }

    public void RunQuery(JiraResource resource,string argument = null,string data = null,string method = "GET")
    {
        string url = string.Format("{0}{1}/", exec_URL, resource.ToString());

        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
        request.ContentType = "application/json";
        request.Method = method;

        string base64Credentials = GetEncodedCredentials();
        request.Headers.Add("Authorization", "Basic " + base64Credentials);

        HttpWebResponse response = request.GetResponse() as HttpWebResponse;

        string result = string.Empty;
        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
        {
            result = reader.ReadToEnd();
        }

        TryJira.Util.Write_To_File(result,"contents.txt");
        Console.WriteLine("Process completed");
    }

    private string GetEncodedCredentials()
    {
        string mergedCredentials = string.Format("{0}:{1}", Username, Password);
        byte[] byteCredentials = UTF8Encoding.UTF8.GetBytes(mergedCredentials);
        return Convert.ToBase64String(byteCredentials);
    }
}

为什么我的第一个URL不能用于代码?任何帮助表示赞赏。

先谢谢

1 个答案:

答案 0 :(得分:0)

当您通过代码启动 URL 时,它使用的 cookie 与通过浏览器在工作 URL 中使用的 cookie 不同。我花了几个小时试图暴力破解它并尝试了各种东西。基本上,如果你使用这个工作 URL 并转到不同的浏览器或私有模式,它是一样的,它不会工作,因为你从来没有在那里进行过身份验证。同样,您可能会收到错误或未经授权的请求错误消息。

这里的解决方案是使用电子邮件和 JIRA API 令牌进行身份验证 - 而不是密码。可在此处找到更多信息:https://community.atlassian.com/t5/Jira-questions/Using-Jira-s-REST-API/qaq-p/1231541

这是我如何让它工作的代码。如果您只想搜索新问题或按任何状态搜索,请使用此 URL 搜索状态“新”:/rest/api/2/search?jql=project=ProjectName%20AND%20status%20=%20%22New%22&fields =状态

using System;
using System.Configuration;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace Jira.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            string result = "N/A";
            string jiraOrgName = ConfigurationManager.AppSettings["jiraOrgName"].ToString();
            string jiraSearchUrl = "https://" + jiraOrgName + ".atlassian.net/rest/api/2/search?jql=project=ProjectName";
            try
            {
                result = PostJsonRequest(jiraSearchUrl);
            }
            catch(Exception e)
            {
                result = e.Message.ToString();
            }

            ViewBag.Json = result.ToString();
            return View();
        }

        private static string GetEncodedCredentials()
        {
            string jiraUserName = ConfigurationManager.AppSettings["jiraUserName"].ToString();
            string jiraApiToken = ConfigurationManager.AppSettings["jiraApiToken"].ToString();
            string mergedCredentials = string.Format("{0}:{1}", jiraUserName, jiraApiToken);
            byte[] byteCredentials = UTF8Encoding.UTF8.GetBytes(mergedCredentials);
            return Convert.ToBase64String(byteCredentials);
        }

        public static string PostJsonRequest(string jiraSearchUrl)
        {
            // Create string to hold JSON response
            string jsonResponse = string.Empty;
            using (var client = new WebClient())
            {
                try
                {
                    client.Encoding = Encoding.UTF8;
                    client.Headers.Set("Authorization", "Basic " + GetEncodedCredentials());
                    client.Headers.Add("Content-Type: application/json");
                    client.Headers.Add("Accept", "application/json");
                    var response = client.DownloadString(jiraSearchUrl);
                    jsonResponse = response;
                }
                catch (WebException ex)
                {
                    // Http Error
                    if (ex.Status == WebExceptionStatus.ProtocolError)
                    {
                        HttpWebResponse wrsp = (HttpWebResponse)ex.Response;
                        var statusCode = (int)wrsp.StatusCode;
                        var msg = wrsp.StatusDescription;
                        throw new HttpException(statusCode, msg);
                    }
                    else
                    {
                        throw new HttpException(500, ex.Message);
                    }
                }
            }
            return jsonResponse;
        }
    }
}