C#Get Request(API) - 如何回调? (代表?)

时间:2016-10-05 07:40:24

标签: c# callback delegates request http-get

我认为对于我想做的事情,我需要某种回调/委托。现在花大约8个小时阅读有关这些回调的内容,观看了一些YouTube视频,但我仍然不完全了解它们是如何工作的。 (到目前为止,较新的使用任何语言的回调。)

按下按钮,我调用函数:

private void btnLoad_Click(object sender, EventArgs e)
{
    GetRequest("http://192.168.68.127/axis-cgi/param.cgi?action=list&group=MediaClip", "root", "root");
}

以下是用于获取请求结果的函数:

public static async void GetRequest(string url, string user, string pass)
{
    using (HttpClientHandler handler = new HttpClientHandler { Credentials = new System.Net.NetworkCredential(user, pass) })
    {
        using (HttpClient client = new HttpClient(handler))
        {
            using (HttpResponseMessage response = await client.GetAsync(url))
            {
                using (HttpContent content = response.Content)
                {
                        string mycontent = await content.ReadAsStringAsync();

                        // --- Do different stuff with "mycontent", depending which button was clicked ---
                        // --- Insert function here ?! ---
                }
            }
        }
    }
}

现在我的问题是,如何判断" GetRequest(字符串url,字符串用户,字符串传递)"在我需要的地方执行特定的功能? 我想我需要......像:

GetRequest(string url, string user, string pass, function())

2 个答案:

答案 0 :(得分:2)

使用async-await,您不需要使用"回调"

更改您的方法以返回"等待"内容。

public static async Task<string> GetRequest(string url, 
                                            string user, 
                                            string pass)
{
    var credentials = new System.Net.NetworkCredential(user, pass);
    using (var handler = new HttpClientHandler { Credentials = credentials })
    {
        using (var client = new HttpClient(handler))
        {
            using (var response = await client.GetAsync(url))
            {
                using (HttpContent content = response.Content)
                {
                    return await content.ReadAsStringAsync();
                }
            }
        }
    }        
}

注意方法Task<string>

的返回类型

然后在任何地方使用它

string content = await GetRequest("url", "admin", "admin");
// Do staff with content

答案 1 :(得分:1)

  1. 定义delegate,定义方法的签名
    属于delegate。在这种情况下:返回值void而不是 参数:
  2. public delegate void YourDelegate();

    1. 定义应该用于GetRequest的回调函数:
    2. public void CallbackFunction() {...}

      1. GetRequest方法中定义参数以使用回调函数:
      2. public void GetRequest(string url, string user, string pass, YourDelegate callback) {...}

        1. GetRequest
        2. 中调用回调

          callback.Invoke();

          1. 执行GetRequest的示例:
          2. GetRequest("http://192.168.68.127/axis-cgi/param.cgi?action=list&group=MediaClip", "root", "root", CallbackFunction);