Azure Functions call http post inside function Azure Functions call http post inside function azure azure

Azure Functions call http post inside function


For anyone else who lands here when searching for HttpClient in Azure functions.

https://docs.microsoft.com/en-us/azure/azure-functions/manage-connections

// Create a single, static HttpClientprivate static HttpClient httpClient = new HttpClient();public static async Task Run(string input){    var response = await httpClient.GetAsync("https://example.com");    // Rest of function}


It is certainly possible and the following code block works just fine in my test function:

using(var client = new HttpClient()){    client.BaseAddress = new Uri("https://www.google.com");    var result = await client.GetAsync("");    string resultContent = await result.Content.ReadAsStringAsync();    log.Info(resultContent);}

It prints out HTML of google.com. POST also works: returns Error 405 (Method Not Allowed)!!1 from google.

Can it be that your callee is failing?


I've done the HTTP post inside Azure Function like so:

using System.Net;using System.Net.Http;using System.Net.Http.Headers;using System.Text;using Newtonsoft.Json;public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, string arg1, string arg2, string arg3, TraceWriter log){    log.Info("C# HTTP trigger function processed a request.");    var text = String.Format("arg1: {0}\narg2: {1}\narg3: {2}", arg1, arg2, arg3);    log.Info(text);    var results = await SendTelegramMessage(text);    log.Info(String.Format("{0}", results));    return req.CreateResponse(HttpStatusCode.OK);}public static async Task<string> SendTelegramMessage(string text){    using (var client = new HttpClient())    {        Dictionary<string, string> dictionary = new Dictionary<string, string>();        dictionary.Add("PARAM1", "VALUE1");        dictionary.Add("PARAM2", text);        string json = JsonConvert.SerializeObject(dictionary);        var requestData = new StringContent(json, Encoding.UTF8, "application/json");        var response = await client.PostAsync(String.Format("url"), requestData);        var result = await response.Content.ReadAsStringAsync();        return result;    }}

As you could guess by the name, I'm using this to send a POST request to a telegram bot