Im going to update work log of an issue in JIRA via the JIRA REST API on c# application. Following codes shows what I have done so far.
HttpWebResponse return this error "The remote server returned an error: (401) Unauthorized." .
I tried this with same credentials and using same data in PHP cURL functions, it works fine and issue work log updated successfully.
This is my Jason converted serialized object : {"update":{"worklog":[{"add":{"comment":"Sample test comment by IJ","timeSpent":"210"}}]}}
protected string RunQuery(JiraResource resource, string argument = null, string data = null, string method = "PUT")
{
// Where;
// resource = issue
// argument = "JIRA-16"
// Data = {"update":{"worklog":[{"add":{"comment":"Sample test comment by IJ","timeSpent":"210"}}]}}
// Method = "PUT"
string url = string.Format("{0}{1}/", m_BaseUrl, resource.ToString());
if (argument != null)
{
url = string.Format("{0}{1}", url, argument);
}
// URL = https://companyname.atlassian.net/rest/api/2/issue/JIRA-16
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.ContentType = "application/json";
request.Method = method;
request.ContentLength = data.Length;
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(data);
}
string base64Credentials = GetEncodedCredentials(); // check below
request.Headers.Add("Authorization", "Basic " + base64Credentials);
HttpWebResponse response = request.GetResponse() as HttpWebResponse;// here returns the error
//The remote server returned an error: (401) Unauthorized.
string result = string.Empty;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}
return result;
}
private string GetEncodedCredentials()
{
string mergedCredentials = string.Format("{0}:{1}", m_Username, m_Password);
byte[] byteCredentials = UTF8Encoding.UTF8.GetBytes(mergedCredentials);
return Convert.ToBase64String(byteCredentials);
}
Where am I doing wrong? please help me.
Likely reason: you are adding authorization header after sending request stream.
var request = WebRequest.Create(url) as HttpWebRequest;
request.ContentType = "application/json";
request.Method = method;
request.ContentLength = data.Length;
// All headers MUST be added before writing to request stream
request.Headers.Add("Authorization", "Basic " + GetEncodedCredentials());
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(data);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.