Migrate WebClient JSON-RPC calls to HttpClient in C# - c#

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));

Related

How to pass Json Content in request Body Using http client with DeleteAsync Method (C#)?

Need to pass Json Content in Request body using http client DeleAsync Method in C#.Not able to pass the Request body in DeleteAsync Method.
HttpClient client=new HttpClient();
var Ids = new[] { 100,202,304,866 };
string endpoint=" URL goes here";
string jsonString = JsonConvert.SerializeObject(Ids);
var RequestBody = new StringContent(jsonString, Encoding.UTF8);
var response = client.DeleteAsync(endpoint,RequestBody).Result;
You can do like this. As far as I know you can't have body in DeleteAsync
object jsonObj;
using (HttpClient client = new HttpClient())
{
var request = new HttpRequestMessage
{
Method = HttpMethod.Delete,
RequestUri = new Uri("yourUrl"),
Content = new StringContent(JsonConvert.SerializeObject(jsonObj), Encoding.UTF8, "application/json")
};
var response = await client.SendAsync(request);

HttpRequestMessage.Method set to Post, but it Gets instead

//request init
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri(client.BaseAddress + ""),
Content = jsonContent
};
Console.WriteLine(request.Method);
var response = await client.SendAsync(request);
Console.WriteLine(response.RequestMessage);
The Request message shows that it was sent as GET, even though I set Method to Post
I think your endpoint is doing a redirect, try turning that off via the HttpClientHandler.
var handler = new HttpClientHandler();
handler.AllowAutoRedirect = false;
var client = new HttpClient(handler);
// Do your work.
your code is doing the right thing. here's a console app that does the same thing, and the outcome is the right one. an Https POST call is done to the configured URL.
using System;
using System.Net.Http;
namespace testapicall
{
class Program
{
static void Main(string[] args)
{
var client = new HttpClient();
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri("https://google.com")
};
Console.WriteLine(request.Method);
var response = client.SendAsync(request).GetAwaiter().GetResult();
Console.WriteLine(response.RequestMessage);
}
}
}
and here's the console log output: Method: POST, RequestUri: https://google.com/', Version: 1.1, Content: , Headers:{}
what is the resource behind the URL you're trying to call doing? Maybe it is redirecting to another resource, by doing a GET request.
I recommend to use the RestClient to execute the Rest APIs.
Please refer the following URL and sample code
https://restsharp.dev/
var client = new RestClient("URL");
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("accept", "application/json");
request.AddParameter("parameter name", "values");
IRestResponse response = client.Execute(request);
var data = (JObject)JsonConvert.DeserializeObject(response.Content);

I can not authorize to hitbtc api from c#

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();
}

CRM 2016 web apis with C#

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();
}

Trying to Post a Slack Message through NameValueCollection using HttpClient.PostAsync instead of WebClient

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);

Categories