I'm quite new to handling json data and web apis but I'm currently creating an application to further my knowledge on them.
At the moment I can do get requests and these work fine however I'm having issues with posts. I'm trying to post json data to Jira Confluence to create a new page.
On https://developer.atlassian.com/confdev/confluence-server-rest-api/confluence-rest-api-examples it gives the below code to make a curl request
curl -u admin:admin -X POST -H 'Content-Type: application/json' -d'{"type":"page","title":"new page",
"ancestors":[{"id":456}], "space":{"key":"TST"},"body":{"storage":{"value":
"<p>This is a new page</p>","representation":"storage"}}}'
http://localhost:8080/confluence/rest/api/content/ | python -mjson.tool
I am currently using the below code and it comes back with a status 200 but I don't see the created page on confluence. I was wondering if anyone could help me out
HttpClient _webRequest = new HttpClient();
byte[] cred = UTF8Encoding.UTF8.GetBytes(credentials);
_webRequest.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(cred));
_webRequest.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
string response = "{\"type\":\"page\",\"title\":\"new page\",\"ancestors\":[{\"id\":40635756}],\"space\":{\"key\":\"VG\"},\"body\":{\"storage\":{\"value\":\"<p>This is a new page</p>\",\"representation\":\"storage\"}}}"
var content = new StringContent(lol, Encoding.UTF8, "application/json");
var result = _webRequest.PostAsync("http://jirasite/confluence/rest/api/content/", content).Result;
Your auth header looks incorrect... You are missing the whitespace after "Basic" it should be like this "Basic xxx".
Please take a look at the following document:
https://developer.atlassian.com/confdev/confluence-server-rest-api/confluence-rest-api-examples?_ga=2.72183699.1804458933.1496916716-1816616270.1496916716#ConfluenceRESTAPIExamples-Createanewpage
Regards
Craig
Related
I've been here for 2 days now driving me nuts.
All I want to do it call a webservice at:
https://use-land-property-data.service.gov.uk/api/v1/datasets
Which returns some JSON object.
It requires the "Authorization" header to be set with an API Key that I have.
I've tried it in POSTMAN and it works.
However trying to get a Webclient or Httpclient version working is currently beyond me. I've tried countless examples here on SO. None return the same responses as POSTMAN. All return "Request Rejected"
e.g.
Using client = New HttpClient()
client.DefaultRequestHeaders.Add("Authorization", "MYKEY")
Dim response = Await client.GetStringAsync("https://use-land-property-data.service.gov.uk/api/v1/datasets")
Return response
End Using
what is the equivalent in httpclient to replicate the postman Authorization header?
Try:
httpClient.DefaultRequestHeaders.Authorization = New AuthenticationHeaderValue("Bearer", "Your Key")
i try to work around converting this to c# but i cant understand the tags like -H others am familiar with like the BVN and secret key are clear to me, but i'm literally at cross road.
curl https://api.paystack.co/bank/resolve_bvn/:BVN
-H "Authorization: Bearer YOUR_SECRET_KEY"
-X GET
this enlightened me but i'm new to using curl
I only want to explain command flags.
-H means request header. In your case, you need to set header with name Authorization to the secret key Bearer YOUR_SECRET_KEY eg Bearer abcd123566 where abcd123566 is your secret key.
-X GET means your request method (HTTP verb) should be GET
-H means the headers of the request. In C# the code would look something like this:
private static HttpClient httpClient = new HttpClient();
var uri = new Uri("https://api.paystack.co/bank/resolve_bvn/:BVN");
var reqMessage = new HttpRequestMessage(HttpMethod.Get, uri);
reqMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_SECRET_KEY")
// Setting the request content (including content-type)
reqMessage.Content = new StringContent("Content of request", Encoding.UTF8, "application/json");
var resp = await httpClient.SendAsync(reqMessage);
You can read more HttpClient and API requests in C# here:
https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netcore-3.1
https://learn.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client
I am writing a WPF application with C# that attempts to make an Google Cloud AutoML API call with HttpClient. I am able to make contact with the server but always get back an "Unauthorized" response. I have scoured StackOverflow and the AutoML documentation for any hint as to how to properly turn the "CURL" request into a simple HTTP request that I can execute programmatically within my C# application, but haven't found anything that gave enough guidance up to this point (hence my question).
Here is the CURL request that I am modeling my HTTP request after:
curl -X POST -H "Content-Type: application/json" \
-H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
https://automl.googleapis.com/v1beta1/projects/image-object-detection/locations/us-central1/models/MyProjectId:predict -d #request.json
There are elements of this request that I cannot figure out how to translate into C#, namely the Authorization: Bearer component. Do I need to somehow find a token and add it to a header or something? If so, how do I acquire this token in string form? That seems to be what I'm really stuck on.
And here is the C# code that I actually have up to this point.
public async Task<object> GetPrediction(string imagePath)
{
string apiKey = "MyApiKey";
string projectId = "MyProjectId";
HttpResponseMessage response;
byte[] img = File.ReadAllBytes(imagePath);
string jsonBody = "{\"payload\":{\"image\":{\"imageBytes\":\"" + Encoding.UTF8.GetString(imgBody) + "\"}}}";
string uri = $"https://automl.googleapis.com/v1beta1/projects/image-object-detection/locations/us-central1/models/{projectId}:predict?key={apiKey}";
string token = “MyToken”;
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, uri);
request.Headers.TryAddWithoutValidation("Content-Type", "application/json");
request.Headers.Authorization = new AuthenticarionHeaderValue(“Bearer”, token);
request.Content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
response = await client.SendAsync(request);
return Task.FromResult(response);
}
This code basically makes contact, then I get back a 401 "unauthorized" status code. Any suggestions or guidance would be greatly appreciated, and if additional information is required, I would be glad to post more. Thanks!
Update:
I modified the code block to include the suggested change from Nkosi, but I am still seeing the same 401 status code.
I am not seeing the Authorization header added to request
-H "Authorization: Bearer $(gcloud auth application-default print-access-token)"
like in the cURL example
set the Authorization on the request before sending it
//...
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "{token-here}");
//...
I'm trying to upload crash manually to HockeyApp using public API. When calling the api link using Postman and uploading crash.log file it works fine but when I try to do the same from C# code I get 404 error.
Here is my code:
string log = ""; //log content
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("*/*"));
var content = new MultipartFormDataContent();
var stringContent = new StringContent(log);
stringContent.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("text/plain");
content.Add(stringContent, "log", "crash.log");
var response = await this.client.PostAsync("https://rink.hockeyapp.net/api/2/apps/[APP_ID]/crashes/upload", content);
}
I was using WireShark to analyse the request that Postman is sending and tried to make mine look exactly the same. The only difference I see is that request from C# code has filename* field in Content-Disposition for the attachment while the one from Postman doesn't:
Content-Disposition: form-data; name="log"; filename="crash.log"; filename*=utf-8''%22crash.log%22
It might be worth mentioning that the code is written in portable library in Xamarin project.
Following #Lukas Spieß sugestion I asked the question on HockeyApp support. Apparently they don't handle quotes in the boundary header. The one thing I missed comparing Postman request and mine.
Here is the solution:
var contentTypeString = content.Headers.ContentType.ToString().Replace("\"", "");
content.Headers.Remove("Content-Type");
content.Headers.TryAddWithoutValidation("Content-Type", contentTypeString);
I am trying to write a program to authenticate to rackspace cloud files. The following command works with curl just fine:
curl -k -X POST https://identity.api.rackspacecloud.com/v2.0/tokens -d '{ "auth":{"RAX-KSKEY:apiKeyCredentials":{"username":"myusername","apiKey":"mykey"}}}' -H "Content-type: application/json"
However, I get a bad request (400) error with the following code:
var client = new RestClient("https://identity.api.rackspacecloud.com/v2.0");
var request = new RestRequest("tokens", Method.POST);
request.RequestFormat = DataFormat.Json;
string serText = "{ \"auth\":{\"RAX-KSKEY:apiKeyCredentials\"{\"username\":\"myusername\",\"apiKey\":\"mykey\"}}}";
request.AddBody(serText);
RestResponse response = (RestResponse)client.Execute(request);
Anybody have any ideas?
So, when adding my json body I need to do so as follows:
request.AddParameter("application/json", serText, ParameterType.RequestBody);
So basically, it was trying to serialize my already serialized json. I found this out by finding some other questions on stack overflow. I would point out this is not explained at all the official "documentation" for RestSharp.