I have a cURL with which I connect to Atlassian JIRA API and search an issue with JQL, filtering issues by project name and status.
This is the cURL command, which works pretty well:
curl -u JIRAUSER:JIRATOKEN -X POST --data '{ "jql": "project = \"QA\" AND status=\"To Do\" " }' -H "Content-Type: application/json" https://jiraserver.atlassian.net/rest/api/2/search
I'm trying to re-build it on c# with httpclient POST method. The code is given below:
static async System.Threading.Tasks.Task Main(string[] args)
{
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://jiraserver.atlassian.net/rest/api/2/search"))
{
var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes("JIRAUSER:JIRA TOKEN"));
request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}");
request.Content = new StringContent("{ \"jql\": \"project = \"QA\" AND status = \"To Do\" }");
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = await httpClient.SendAsync(request);
Console.WriteLine(response);
}
}
}
response returns the following error:
StatusCode: 400, ReasonPhrase: '', Version: 1.1, Content:
System.Net.Http.HttpConnectionResponseContent
And in System.Diagnostics.Debug.Write I get the following error:
error CS0428: Cannot convert method group 'Write' to non-delegate type
'object'. Did you intend to invoke the method?
Please give me some hint or I'm about to hang myself...
I'd suggest using JIRA SDK to interact with your JIRA instance -> https://bitbucket.org/farmas/atlassian.net-sdk/src/master/.
Basically, set of steps are
1) initiate jira client:
var jiraClient = Jira.CreateRestClient(<jiraURL>, <jiraUserName>, <jiraUserPwd>);
2) connect to jira, and pull based on search criteria:
var jql = "project = QA + " AND status in (To Do)";
IEnumerable<Atlassian.Jira.Issue> jiraIssues = AsyncTasker.GetIssuesFromJQL(jiraClient, jql, 999);
3) then, you can enumerate in the pulled issues
...
foreach(var issue in jiraIssues)
{
/*
... for example, some of the available attributes are:
issue.Key.Value
issue.Summary
issue.Description
issue.Updated
String.Format("{0}/browse/{1}", jiraURL.TrimEnd('/') , issue.Key.Value)
...
*/
}
on the side note, it's advisable not to use using(... = new HttpClient()){....}
Related
I am trying to Post a simple Json object using RestSharp to add a new product. I'm getting an error response from the server
"{"status":400,"error":"There was a problem in the JSON you submitted: unexpected character (after ) at line 1, column 2 [parse.c:724] in '{'product':{'name':'Product name','opt1':'Colour'}}"}"
My code:
////
var json = "{\'product\':{\'name\':\'Product name\',\'opt1\':\'Colour\'}}";
IRestClient restClient = new RestClient();
IRestRequest request = new RestRequest()
{
Resource = "https://api.targetsite.com/products/"
};
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Accept", "application/xml");
request.AddHeader("authorization", "Bearer " + token);
request.RequestFormat = DataFormat.Json;
request.AddJsonBody(json);
IRestResponse response = restClient.Post(request);
////
I managed to achive the result I wanted using a curl statment but I would like to do it using RestSharp.
Curl statment -
curl -X POST -H "Content-type: application/json" -H "Authorization: Bearer <ACCESS_TOKEN>"
https://api.targetsite.com/products/ -d '{"product":{"name":"Product name","opt1":"Colour"}}'
This HttpClient call also works fine
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.targetsite.com/products/"))
{
request.Headers.TryAddWithoutValidation("Authorization", "Bearer <ACCESS_TOKEN>");
request.Content = new StringContent("{\"product\":{\"name\":\"Product name\",\"opt1\":\"Colour\"}}");
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
var response = await httpClient.SendAsync(request);
}
}
It looks like a limitation on the API you are calling.
When you send the json with curl, you're using different delimiters (" instead of ').
My guess is that the API you're calling doesn't properly deserialize the JSON when ' is used.
What you can try is replacing the escaped ' with " or replace this line in your code : request.AddJsonBody(json)
with
request.AddJsonBody(Newtonsoft.Json.JsonConvert.DeserializeObject(json)) provided that you have installed the newtonsoft package.
Im trying to do this curl request (from API documentation) in HttpClient:
Please not that the code below is just copied from their documentation and does not contain any of my information.
POST /oauth/token (get access token)
$ curl -v -X POST https://api.tink.com/api/v1/oauth/token \
-d 'code=1a513b99126ade1e7718135019fd119a' \
-d 'client_id=YOUR_CLIENT_ID' \
-d 'client_secret=YOUR_CLIENT_SECRET' \
-d 'grant_type=authorization_code'
{
"access_token": "78b0525677c7414e8b202c48be57f3da",
"token_type": "bearer",
"expires_in": 7200,
"refresh_token": "33f10ce3cb1941b8a274af53da03f361",
"scope": "accounts:read,statistics:read,transactions:read,user:read"
}
I've tried to make a post request to the oauth/token endpoint both with all the information requested as header (with an empty body) and as a json document (with and without the headers).
When I only have the information in the headers I get a 401 back, but I've verified that all the data is correct. All other ways that I've tried has generated a 400.
As far as I can understand the json below the curl is the response, but Im not accustomed at all to curl.
There's a handy site here: https://curl.olsh.me/
I wouldn't recommend sending secrets over the web, so be sure to anonymise the values first and translate them back after.
So for the command you've pasted you'd get:
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.tink.com/api/v1/oauth/token"))
{
var contentList = new List<string>();
contentList.Add("code=1a513b99126ade1e7718135019fd119a");
contentList.Add("client_id=YOUR_CLIENT_ID");
contentList.Add("client_secret=YOUR_CLIENT_SECRET");
contentList.Add("grant_type=authorization_code");
request.Content = new StringContent(string.Join("&", contentList));
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
var response = await httpClient.SendAsync(request);
}
}
The 401 headers you are getting back may be due to passing in the wrong id and secret, I presume there is a way for you to get test credentials.
I'm facing a strange error with the usage of the GITHUB API.
When I contact them with cURL it's like:
curl.exe -H "Accept: application/vnd.github.cloud-9-preview+json+scim" -H "Authorization: Bearer TOKEN" https://api.github.com/scim/v2/organizations/[ORG]/Users
When I try to take it to C#, if became:
using (var cl = new HttpClient())
{
cl.DefaultRequestHeaders.Add("Accept", "application/vnd.github.cloud-9-preview+json+scim");
cl.DefaultRequestHeaders.Add("Authorization", "Bearer " + "TOKEN");
var val = cl.GetStringAsync("https://api.github.com/scim/v2/organizations/[ORG]/Users").Result;
}
When I run my cURL everything works fine but when I try the same on C# I got a 403 Error.
Could it be related to the "Accept" non standard field?
I find out that the GITHUB API requires to have the User-Agent header Set.
Setting it as "curl" made it.
using (var cl = new HttpClient())
{
cl.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/vnd.github.cloud-9-preview+json+scim"));
cl.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "token");
cl.DefaultRequestHeaders.UserAgent.Add(new System.Net.Http.Headers.ProductInfoHeaderValue("curl", "7.46.0"));
var val = cl.GetStringAsync("https://api.github.com/scim/v2/organizations/[ORG]/Users").Result;
}
I am trying to convert the following cURL command to C# using restSharp
so that I can mark my automated Browserstack tests passed or failed.
curl -u "user:password" -X PUT -H "Content-Type: application/json" -d "{\"status\":\"<new-status>\", \"reason\":\"<reason text>\"}" https://www.browserstack.com/automate/sessions/<session-id>.json
Please note I am very new to C# I have the following code that currently returns an empty json response, I know I am on the right path as changing the request method to POST returns details (as expected) for my session/test:
private string markTestPassedorFail(string sesID)
{
var Client = new RestClient();
var Request = new RestRequest();
string sResponse = "";
Client.BaseUrl = new Uri(CapConf.BROWSERSTACK_SESSIONS_URL);
Client.Authenticator = new HttpBasicAuthenticator(CapConf.BROWSERSTACK_USER_NAME, CapConf.BROWSERSTACK_KEY_PASS);
Request.Resource = sesID + ".json";
Request.Method = Method.PUT;
Request.AddHeader("Content-Type", "application/json");
Request.AddJsonBody("{\"status\":\"failed\", \"reason\":\"failed\"}");
try
{
IRestResponse response = Client.Execute(Request);
sResponse = response.Content;
}
catch (Exception ex)
{
Console.WriteLine("Error Marking Test Passed or Fail : \n" + ex.Message);
}
return sResponse;
}
Have you tried the sample code snippet shared in their documentation here - https://www.browserstack.com/automate/c-sharp
I just pulled up bits of the code snippet there and was able to setup a sample test run, fetch the session ID and later update the session status via REST API.
Sample test -
https://www.browserstack.com/automate/c-sharp#getting-started
Session ID -
https://www.browserstack.com/automate/c-sharp#session-id
Session status update via REST API -
https://www.browserstack.com/automate/c-sharp#rest-api
Refer to the following gist:
https://gist.github.com/ashwingonsalves/56d7724671054bf623081bdcb30d40b8
I'm trying to write a specific curl request in C#, and I keep getting a 500 server error response from the server. This curl request essentially makes a post request to an API by the company Highwinds. This request sends json data, and sets the Auth Bearer token header.
This is the curl request that works fine (note that I've replaced my actual bearer token with {token} and my actual account id with {accountId} to obfuscate that info):
curl -H "Authorization: Bearer {token}" -H "Content-Type: application/json" -d "#data.json" "https://striketracker.highwinds.com/api/accounts/{accountId}/purge"
Here's the C# code that gives me a generic 500 server error from the Highwinds API (note that I've replaced my actual bearer token with {token}, my actual account id with {accountId}, and the url in the json string with {url}, in order to obfuscate that personal info):
var accountId = "{accountId}";
var purgeURI = string.Format("https://striketracker.highwinds.com/api/accounts/{0}/purge", {accountId});
var query =
#"{""list"": [{""url"": ""{url}"",""recursive"": true}]}";
var token = {token};
using (var httpClient = new HttpClient())
{
var url = new Uri(purgeURI);
using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, url))
{
httpRequestMessage.Headers.Add(System.Net.HttpRequestHeader.Authorization.ToString(),
string.Format("Bearer {0}", token));
httpRequestMessage.Content = new StringContent(query,
Encoding.UTF8,
"application/json");
await httpClient.SendAsync(httpRequestMessage).ContinueWith(task =>
{
var response = task.Result;
var blah = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
});
}
}
Thanks!
*Update: The following line of code was added to remove the Expect header that HttpRequest adds to a request by default. After removing this header I was able to get Highwinds API to accept the request without bombing.
"request.ServicePoint.Expect100Continue = false;"
My best recommendation would be to proxy both requests through something like tcpmon http://archive.apache.org/dist/ws/tcpmon/1.0/ (Basically run the server and point to local host and have tcpmon redirect the request to striketracker.highwinds.com). Try it from curl and from your source and you should be able to see what's different between the requests.