my code is:
HitBtcApi.HitBtcApi hitbtc = new HitBtcApi.HitBtcApi();
hitbtc.Authorize("xxx", "xxx");
RestRequest request2 = new RestRequest("/api/2/account/balance", method.GET);
var x= await hitbtc.Execute(request2, true);
MessageBox.Show(x.content.ToString());
this error rising when running:
{"error":{"code":1001,"message":"Authorization required","description":""}} but when i use "/api/2/public/symbol" instead of "/api/2/account/balance" it work. please help me. thanks.
Did you activate the access right to the specific API for your API key?
https://hitbtc.com/settings/api-keys
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new
System.Net.Http.Headers.AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
Encoding.ASCII.GetBytes(
"user:pass")));
var result = await (await client.GetAsync("https://api.hitbtc.com/api/2/trading/balance")).Content
.ReadAsStringAsync();
}
Related
I would like to accomplish the same thing as this using HttpClient in .Net 6
using (var webClient = new WebClient())
{
// Required to prevent HTTP 401: Unauthorized messages
webClient.Credentials = new NetworkCredential(username, password);
// API Doc: http://kodi.wiki/view/JSON-RPC_API/v6
var json = "{\"jsonrpc\":\"2.0\",\"method\":\"GUI.ShowNotification\",\"params\":{\"title\":\"This is the title of the message\",\"message\":\"This is the body of the message\"},\"id\":1}";
response = webClient.UploadString($"http://{server}:{port}/jsonrpc", "POST", json);
}
If anyone has any insight on this it would be greatly appreciated.
using HttpClient client = new();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes($"{username}:{password}")))
var json = "{\"jsonrpc\":\"2.0\",\"method\":\"GUI.ShowNotification\",\"params\":{\"title\":\"This is the title of the message\",\"message\":\"This is the body of the message\"},\"id\":1}";
var response = await client.PostAsync($"http://{server}:{port}/jsonrpc", new StringContent(json));
Well Im new in Xamarin and I'm developing and App, the authentication is JWT based.
Im using a HttpClient and setting the AuthenticationHeaders but It always returns Unauthorized when I try it on Postman it Works but I can't make it work in my app.
Here is how im trying to do it:
var client = new HttpClient(new HttpClientHandler());
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("JWT", accessToken);
client.BaseAddress = new Uri(urlBase);
var url = string.Format("{0}{1}", servicePrefix, controller);
var response = await client.GetAsync(url);
Try something like this
using (var client = new HttpClient())
{
var uri = new Uri(string.Format($"{<yourURLString>}", string.Empty));
var jsonTransport = "";
var jsonPayload = new StringContent(jsonTransport, Encoding.UTF8, "application/json");
//client.DefaultRequestHeaders.Add("Content-type", "application/json");
client.DefaultRequestHeaders.Add("Authorization", "JWT " + accessToken);
var response = await client.PostAsync(uri, jsonPayload);
string responseContent = await response.Content.ReadAsStringAsync();
}
then deserialize the responseContent to your object using JsonConvert.DeserializeObject
Note: Below are code samples, edit to your own objects
SubscriptionResponse profileResponse = JsonConvert.DeserializeObject<SubscriptionResponse>(responseContent);
then if your method returns something, use the return statement. Something like this
return profileResponse.Data.Subscriptions;
If you're using a get, this could be a guide
var uri = new Uri(string.Format($"{<yourURLHere>}", string.Empty));
client.DefaultRequestHeaders.Add("Authorization", "JWT " + accessToken);
var httpResponse = await client.GetAsync(uri);
var responseContent = await httpResponse.Content.ReadAsStringAsync();
then deserialize your string response
Note: this is a sample - edit to your model (You may use PostMan to get the response format in JSON and model it in C#)
var UserDetailResponse = JsonConvert.DeserializeObject<UserDetail>(responseContent);
return UserDetailResponse;
I'm trying to call the Shopware REST API from c#. Shopware has documentation for calling the API using curl, and mostly I can convert this to c# and HttpClient, but for some options I just don't know what headers to set:
The Shop is behind a basic htaccess-auth and has the Shopware auth using an apikey. My code so far:
var handler = new System.Net.Http.HttpClientHandler { Credentials = new NetworkCredential(htaccessUsername, htaccessPassword) });
var client = new System.Net.Http.HttpClient(handler);
using (var requestMessage = new HttpRequestMessage(HttpMethod.Get, apiUrl + "orders?limit=20"))
{
var encodedStr = Convert.ToBase64String(Encoding.Default.GetBytes($"{username}:{apiKey}"));
var authorizationKey = "Basic" + " " + encodedStr;
requestMessage.Headers.Add("Authorization", authorizationKey);
// curl_setopt($this->cURL, CURLOPT_RETURNTRANSFER, true);
// curl_setopt($this->cURL, CURLOPT_FOLLOWLOCATION, false);
// curl_setopt($this->cURL, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
// curl_setopt(
// $this->cURL,
// CURLOPT_HTTPHEADER,
// ['Content-Type: application/json; charset=utf-8']
// );
using (var responseMessage = await client.SendAsync(requestMessage))
{
var data = await responseMessage.Content.ReadAsStringAsync();
System.Diagnostics.Trace.WriteLine(data);
}
}
Basic htaccess auth is working, but the Shopware auth does fail with the following response in data:
"{\"success\":false,\"message\":\"Invalid or missing auth\"}"
I guess I Need to somehow achieve curl_setopt($this->cURL, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST); in c#, but I found no clue how to convert These curl options to a header.
Any help?
Looks like the answer for you is here:
var credCache = new CredentialCache();
var basicCred = new NetworkCredential(htaccessUsername, htaccessPassword);
var digestCred = new NetworkCredential(username, apiKey);
credCache.Add(new Uri("http://.com/"), "Basic", basicCred);
credCache.Add(new Uri("http://.com/"), "Digest", digestCred);
var httpClient = new HttpClient(new HttpClientHandler { Credentials = credCache });
We have CRM 2016 on premise and want to consume the API using c# :
var credentials = new NetworkCredential(username, password);
HttpClient client = new HttpClient(new HttpClientHandler() {Credentials = credentials});
client.BaseAddress = new Uri("https://xxx.elluciancrmrecruit.com/api/data/v8.0/datatel_events");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("datatel_events?$orderby=datatel_eventname").Result;
if (response.IsSuccessStatusCode)
{
var yourcustomobjects = response.Content.ReadAsStringAsync();
}
else
{
//Something has gone wrong, handle it here
}
But it always return HTML page says try later instead of the json response.
You should query the OData endpoint to get the information you are looking for assuming date1_events is a custom entity (although the naming convention seems to be off).
As an example to query contacts:
var credentials = new NetworkCredential(username, password);
var client = new HttpClient(new HttpClientHandler() {Credentials = credentials})
{
BaseAddress = new Uri("https://xxx.elluciancrmrecruit.com/api/data/v8.0/")
};
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.GetAsync("accounts?$top=1").Result;
if (response.IsSuccessStatusCode)
{
var yourcustomobjects = response.Content.ReadAsStringAsync();
}
I am trying to use HttpClient to post a NameValueCollection to a specific Url. I have the code working using WebClient, but I'm trying to figure out if it is possible to do using HttpClient.
Below, you will find my working code that uses WebClient:
var payloadJson = JsonConvert.SerializeObject(new { channel, username, text });
using (var client = new WebClient())
{
var data = new NameValueCollection();
data["payload"] = payloadJson;
var response = client.UploadValues(_uri, "POST", data);
var responseText = _encoding.GetString(response);
}
I'm using this code to try to post a message to a Slack Channel using a web integration. Is there a way to implement this same functionality while using HttpClient?
The Slack error that I receive when I try to use HttpClient is "missing_text_or_fallback_or_attachment".
Thanks in advance for any help!
Using HttpClient
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://yourdomain.com/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var data = new NameValueCollection();
data["payload"] = payloadJson;
StringContent content = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");
try
{
HttpResponseMessage response = await client.PostAsync("api/yourcontroller", content);
if (response.IsSuccessStatusCode)
{
//MessageBox.Show("Upload Successful", "Success", MessageBoxButtons.OK);
}
}
catch (Exception)
{
// ignored
}
}
While you are tagging #slack in the question, I suggest you to use Slack.Webhooks nuget package.
Example usage I found is in here;
https://volkanpaksoy.com/archive/2017/04/11/Integrating-c-applications-with-slack/
var url = "{Webhook URL created in Step 2}";
var slackClient = new SlackClient(url);
var slackMessage = new SlackMessage
{
Channel = "#general",
Text = "New message coming in!",
IconEmoji = Emoji.CreditCard,
Username = "any-name-would-do"
};
slackClient.Post(slackMessage);