我正在尝试使用HttpWebRequest创建对我们内部Jira服务器的REST API调用。但是不知何故,我不断收到(400)错误的请求错误。我也尝试过使用WebClient和其他方法,但是似乎找不到正确的方法。有什么建议吗?
URL 是正确的
用户是正确的
密码是正确的
JSON数据也正确
必须有另一种访问远程服务器的方式吗?我一直在搜索,但似乎找不到解决方法。
public static void CreateJiraRequest(JiraApiObject.RootObject jiraApiObject)
{
string url = "https://jira-test.ch.*********.net/rest/api/latest/issue/";
string user = "peno.ch";
string password = "**********";
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json";
request.Credentials = new System.Net.NetworkCredential(user, password);
string data = JsonConvert.SerializeObject(jiraApiObject);
using (var webStream = request.GetRequestStream())
using (var requestWriter = new StreamWriter(webStream, System.Text.Encoding.ASCII))
{
requestWriter.Write(data);
}
try
{
var webResponse = request.GetResponse();
using (var responseReader = new StreamReader(webResponse.GetResponseStream()))
{
string response = responseReader.ReadToEnd();
}
}
catch (Exception ex)
{
throw ex;
}
}
{
"fields": {
"project":
{
"key": "FOO"
},
"summary": "Test the REST API",
"issuetype": {
"name": "Task"
}
}
}
在request.GetResponse();
上输入try块时会发生异常
其他信息:远程服务器返回错误:(400)错误的请求。
访问Jira Wiki here
答案 0 :(得分:2)
上面的代码中的问题是Jira需要编码的凭据。如果不对凭据进行编码,那么Jira服务器将返回400 Bad Request错误,并且没有特定信息。
我编写了两个新功能,一个用于API请求,另一个用于凭据的编码。
[TestClass]
public class FruitTests
{
[TestMethod]
public void WhichConstructorIsUsed()
{
var fruits = new List<IFruit>();
fruits.Add(new Apple(Colors.Red, 5));
fruits.Add(new Banana(Colors.Yellow, 20));
var clonedFruits = fruits.Select(f => new Apple(f));
Console.WriteLine(string.Join("\n", clonedFruits));
}
}
public static string PostJsonRequest(string endpoint, string userid, string password, string json)
{
// Create string to hold JSON response
string jsonResponse = string.Empty;
using (var client = new WebClient())
{
try
{
client.Encoding = System.Text.Encoding.UTF8;
client.Headers.Set("Authorization", "Basic " + GetEncodedCredentials(userid, password));
client.Headers.Add("Content-Type: application/json");
client.Headers.Add("Accept", "application/json");
var uri = new Uri(endpoint);
var response = client.UploadString(uri, "POST", json);
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;
}