.net Azure 函数在函数内部调用 http post

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42482223/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 09:52:53  来源:igfitidea点击:

Azure Functions call http post inside function

.netsocketsazuredotnet-httpclientazure-functions

提问by Przemek Marcinkiewicz

Is it possible to create HTTP(s) post request inside Azure Function? I am trying to create a custom webhook that is listening to one service and when triggered then its calling another service over HTTP using post.

是否可以在 Azure Function 中创建 HTTP(s) 发布请求?我正在尝试创建一个自定义 webhook,它正在侦听一个服务,并在触发时使用 post 通过 HTTP 调用另一个服务。

My code looks like that:

我的代码看起来像这样:

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{

    BitbucketRequest data = await req.Content.ReadAsAsync<BitbucketRequest>();
    //DO STH WITH DATA TO GET e.g. USER STORY ID

    using(var client = new HttpClient()){
        client.BaseAddress = new Uri("https://SOME_TARGETPROCESS_URL/api/v1");
        var body = new { EntityState = new  { Id = 174 } };
        var result = await client.PostAsJsonAsync(
                       "/UserStories/7034/?resultFormat=json&access_token=MYACCESSTOKEN",
                       body);
        string resultContent = await result.Content.ReadAsStringAsync();
    }

    return req.CreateResponse<string>(HttpStatusCode.OK,"OKOK");
}

I suppose the problem is that currently HttpRequestMessage is occupying web socket and I can not create new Http Request.

我想问题是当前 HttpRequestMessage 正在占用网络套接字,我无法创建新的 Http 请求。

Errors that I found in Exceptions details:

我在异常详细信息中发现的错误:

  • The underlying connection was closed: An unexpected error occurred on a send.
  • Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
  • Socket Exception Error Code : 10054
  • 基础连接已关闭:发送时发生意外错误。
  • 无法从传输连接读取数据:远程主机强行关闭了现有连接。
  • 套接字异常错误代码:10054

回答by Mikhail Shilkov

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. POSTalso works: returns Error 405 (Method Not Allowed)!!1 from google.

它打印出 google.com 的 HTML。POST也有效:从谷歌返回错误 405(方法不允许)!!1。

Can it be that your callee is failing?

可能是你的被叫方失败了?

回答by 4c74356b41

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

我已经在 Azure Function 中完成了 HTTP 帖子,如下所示:

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

正如您从名称中猜到的那样,我正在使用它向电报机器人发送 POST 请求

回答by Ryan E.

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

对于在 Azure 函数中搜索 HttpClient 时到达这里的任何其他人。

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

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

// Create a single, static HttpClient
private static HttpClient httpClient = new HttpClient();

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

回答by Tarjei Utnes

I just spent quite a few hours myself trying to get this to work. This was in NodeJS. The thing I figured out, was that I apparently needed to have an endpoint running HTTPS, and with a valid certificate.

我自己花了好几个小时试图让它发挥作用。这是在 NodeJS 中。我发现的事情是,我显然需要一个运行 HTTPS 的端点,并有一个有效的证书。

Not sure if this is documented anywhere.

不确定这是否记录在任何地方。