0

我一直在搜索并研究如何获得 Jira REST 响应已经有一段时间了。问题是当它到达此代码时,将引发异常,无论是 BAD REQUEST 还是 INTERNAL SERVER ERROR。

HttpWebResponse response = request.GetResponse() as HttpWebResponse;

它永远不会超出此代码。相反,我期待:

}
  "errorMessages": [],
  "errors": {
  "message": "An error occured ... "
  }
}

对于错误消息或:

}
  "id": "11600",
  "key": "RP-547",
  "self": "http://jira.com/rest/api/2/issue/11600"
}

关于成功。

有什么我错过或误解的吗?我如何获得预期的结果?

一些额外的信息:

HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.ContentType = "application/json";
request.Accept = "application/json";
request.Method = method; //POST
if (data != null)
{
    using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
    {
        writer.Write(data);
    }
}
string base64Credentials = GetEncodedCredentials();
request.Headers.Add("Authorization", "Basic " + base64Credentials);
string result = string.Empty;
HttpWebResponse response = request.GetResponse() as HttpWebResponse; //breaks here
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
    result = reader.ReadToEnd();
}
4

1 回答 1

0

HttpWebRequest 为非 200 http 响应生成异常。您需要在 catch 子句中处理错误响应。

帮助页面

注意 如果引发 WebException,请使用异常的 Response 和 Status 属性来确定来自服务器的响应。

另请参阅此问题

或者,如果您使用的是 .Net 4.5,则可以使用 HttpClient 而不是 WebRequest。

于 2013-07-23T02:57:07.387 回答