I want to send a simple message using the service Clickatell.
I don't want to read the response, it will be simple GET request to send a message.
The service provides the request looks like:
https://platform.clickatell.com/messages/http/send?apiKey=xxxxxxxxxxxxxxxx==&to=xxxxxxxxxxx&content=Test+message+text
I checked it with curl
curl "https://platform.clickatell.com/messages/http/send?apiKey=apiKEY==&to=NUMBER&content=Test+message+text"
and it's working really fine.
I try to use it with my Windows Forms application with HTTP request
Below is the code which I provided:
var client2 = new HttpClient();
client2.GetAsync("https://platform.clickatell.com/messages/http/send?apiKey=apiKEY==&to=NUMBER&content=Test+message+text");
App.Write("SMS SEND!");
I have info that SMS send, but I didn't receive it. My friend use my code in the .NET application and it's working for him.
Do I miss something?
Maybe it's really worth to mention I need to add to References manually using System.Net.Http;
EDIT:
I tried to add to do it async, so I edit my code to:
static void sendSMS()
{
var client2 = new HttpClient();
var task = client2.GetAsync("https://platform.clickatell.com/messages/http/send?apiKey=API_KEY==&to=MY_NUMBER&content=Test+message+text");
task.Wait();
App.Write("SMS SEND!");
}
But now the SMS SEND message in the application is not shown.
Ok I know You use .NET 4.5 and You probably have problem with a exeption
"The underlying connection was closed: An unexpected error occurred on a send"
The right code it looks like this: (You must add 'SecurityProtocol 'before reqeust):
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
var client2 = new HttpClient();
client2.GetAsync("https://platform.clickatell.com/messages/http/send?apiKey=apiKEY==&to=NUMBER&content=Test+message+text").Result;
More details herehttps://stackoverflow.com/a/32789483/5816153
Related
I have a .pem certificate file which is used to communicate between two servers. For communication I have written a program in C# like this:
var client = new RestClient("https://aaaaa.com:1111");
client.ClientCertificates = new X509CertificateCollection();
client.ClientCertificates.Add(new X509Certificate(#"C:\Users\aaa\Desktop\bbb.pem"));
var request = new RestRequest("/qqq/www", Method.POST);
request.AddJsonBody(new { create = new { msgBdy="Test" } });
var response = client.Execute(request);
Console.WriteLine(response.StatusCode);
//The underlying connection was closed: An unexpected error occurred on a send.
When I post the request through SoapUI it goes through, but when I try to send it through Postman or the above C# program it doesn't.
Screenshot from wireshark is below:
The change cipher spec event is called for the successful API call but through postman and c# application this event is never called.
I have tried to do this as explained in this article as well https://www.codeproject.com/Articles/326574/An-Introduction-to-Mutual-SSL-Authentication but that also didn't work.
How can I fix this issue.
I am using HttpClient PostAsync to send data to a URI. However, the following code doesn't behave as expected:
using (var client = new HttpClient())
{
var values = new Dictionary<string, string>
{
{"cpm_site_id",TOKEN},
{"apikey",API_KEY},
{"cpm_amount",input.Amount},
{"cpm_currency",input.Currency},
{"cpm_trans_id",input.Id},
{"cpm_custom",input.Custom},
};
// Get the parameters in the url encoded format
var content = new FormUrlEncodedContent(values);
//Send request
var response = await client.PostAsync(new Uri(Urls.GetUrl(Methods.Pay, IS_PRODUCTION_SITE)), content);
When the client closes their browser, I want to receive an event notification to call this code, send the above data to the client, and open a new browser instance to perform additional actions. However, this code doesn't accomplish this and I'm not sure exactly why.
I think you'll need to use something like Selenium to automate a web browser. The HttpClient can perform HTTP functions, but does not work like a web browser does.
See this SO post for a 'hello world' example
See this SO post for an example of capturing the browser close event. I've not done this with C#, but I'd imagine it'll be similar to this JAVA example.
I have created a new Webapi2 project and I am trying to call an external web service using this code:
WebServiceAuthResult authResult = new WebServiceAuthResult();
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);
try
{
var response = await httpClient.PostAsync(url, null);
var responseContent = await response.Content.ReadAsStringAsync();
authResult = JsonConvert.DeserializeObject<WebServiceAuthResult>(responseContent);
}
catch (Exception ex)
{
}
}
I am getting this error:
Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
I have used the exact same code in a UWP project and it works perfectly - So I am guessing there's something wrong in my project set up.
I've looked at Google and other StackOverflow questions about this but they all suggest an issue with the web service - but I know this is working as I can test using my UWP project.
Can anyone suggest anything for me to try?
As is usually the case with these questions the answer is a one liner but has taken 4 hours to resolve!
By adding this line of code the connection to the web service is successful:
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
I've added the code in the using statement but I think it's only required once so if anyone can tell me where is the best place to add this code and why I need it in my WebApi project and not my UWP project?
I can't find an example of sending message by telegram protocol from C#. I tried to use this but failed.
Can you give me any examples?
TLSharp is basic implementation of Telegram API on C#. See it here https://github.com/sochix/TLSharp
You can use the WTelegramClient library to connect to Telegram Client API protocol (as a user, not a bot)
The library is very complete but also very easy to use. Follow the README on GitHub for an easy introduction.
To send a message to someone can be as simple as:
using TL;
using var client = new WTelegram.Client(); // or Client(Environment.GetEnvironmentVariable)
await client.LoginUserIfNeeded();
var result = await client.Contacts_ResolveUsername("USERNAME");
await client.SendMessageAsync(result.User, "Hello");
//or by phone number:
//var result = await client.Contacts_ImportContacts(new[] { new InputPhoneContact { phone = "+PHONENUMBER" } });
//client.SendMessageAsync(result.users[result.imported[0].user_id], "Hello");
For my bot I use Telegram.Bot nuget package. Full sample code is here.
Here is example of sending message in reply to incoming message.
// create bot instance
var bot = new TelegramBotClient("YourApiToken");
// test your api configured correctly
var me = await bot.GetMeAsync();
Console.WriteLine($"{me.Username} started");
// start listening for incoming messages
while (true)
{
//get incoming messages
var updates = await bot.GetUpdatesAsync(offset);
foreach (var update in updates)
{
// send response to incoming message
await bot.SendTextMessageAsync(message.Chat.Id,"The Matrix has you...");
}
}
The simplest way is to send http request directly to the Telegram BOT API as url string, you may test those url strings even in your browser, please see details in my another answer here:
https://stackoverflow.com/a/57341990/11687179
at the first step you have to generate a bot in botfather then use the code in bellow in C#
private void SendMessage(string msg)
{
string url = "https://api.telegram.org/{botid}:{botkey}/sendMessage?chat_id={#ChanalName}&text={0}";
WebClient Client = new WebClient();
/// If you need to use proxy
if (Program.UseProxy)
{
/// proxy elements are variable in Program.cs
Client.Proxy = new WebProxy(Program.ProxyUrl, Program.ProxyPort);
Client.Proxy.Credentials = new NetworkCredential("hjolany", "klojorasic");
}
Client.DownloadString(string.Format(url, msg));
}));
}
Telegram has an official API that can do exactly what you need, you will have to look into http requests though..
Here is the documentation on sending a message:
Function
messages.sendMessage
Params
peer InputPeer User or chat where a message will be sent
message string Message text
random_id long Unique client message ID required to prevent message resending
Query example
(messages.sendMessage (inputPeerSelf) "Hello, me!" 12345678901)
Return errors
Code Type Description
400 BAD_REQUEST PEER_ID_INVALID Invalid peer
400 BAD_REQUEST MESSAGE_EMPTY Empty or invalid UTF8 message was sent
400 BAD_REQUEST MESSAGE_TOO_LONG Message was too long.
Current maximum length is 4096 UTF8 characters
For the full documentation go here.
I am trying to send a HTTP GET request to a service secured with BASIC authentication and https. If I use the RESTClient Firefox plugin to do so there is no problem. I am defining the basic-header and sending the GET to the url and I am getting the answer (data in json).
Now I am working on a Windows Store App in C# which is meant to consume the service. I enabled all required capabilities in the manifest and wrote the following method:
private async void HttpRequest()
{
string basic = "Basic ...........";
Uri testuri = new Uri(#"https://...Servlet");
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", basic);
Task<HttpResponseMessage> response = client.GetAsync(testuri);
var text = await response;
var message = text.RequestMessage;
}
I tried out many different possibilites like getting the response-string but everything lead to an 401 Status Code answer from the Server.
I looked at many similar problems and my understanding of the communication is the following: Client request -> Server response with 401 -> Client sends Authorization header -> Server response with 200 (OK)
What I don't understand is why I am getting the 401 "Unauthorized" Status Code although I am sending the Authorization header right at the beginning. It would be interesting if someone knows how this is handled in the RESTClient.
The BASIC header is definetly correct I was comparing it with the one in the RESTClient.
It would be great if someone could help me with this.
Thanks in advance and kind regards,
Max
Was having a similar problem, i added a HttpClientHandler to HttpClient.
var httpClientHandler = new HttpClientHandler();
httpClientHandler.Credentials = new System.Net.NetworkCredential("","")
var httpClient = new HttpClient(httpClientHandler);
Credentials should be encoded, before adding to the header. I tested it in WPF app, It works...
string _auth = string.Format("{0}:{1}", "username", "password");
string _enc = Convert.ToBase64String(Encoding.UTF8.GetBytes(_auth));
string _basic = string.Format("{0} {1}", "Basic", _enc);
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization",_basic);