【问题标题】:How to fix 'An invalid request URI was provided. The request URI must either be an absolute URI or BaseAddress must be set'如何修复“提供了无效的请求 URI”。请求 URI 必须是绝对 URI 或必须设置 BaseAddress'
【发布时间】:2020-01-07 20:52:48
【问题描述】:

当我尝试使用 HttpClient.GetStringAsync 发出 GET 请求时,我的程序会爆炸。
这是错误消息:
An invalid request URI was provided. The request URI must either be an absolute URI or BaseAddress must be set.

假设我的程序根据用户选择的 IP 向其不同的变体发出请求,以了解哪个可用。 例如: 用户选择“192.168.0.20”,那么我的程序必须向“192.168.0.1, 192.168.0.2, ...”发出请求

private static readonly HttpClient client = new HttpClient();
            try
            {
                string[] ips = cbxIps.SelectedValue.ToString().Split('.');
                string ip = ips[0] + "." + ips[1] + "." + ips[2] + ".";
                for (int i = 1; i < 255; i++)
                {
                    var responseString = client.GetStringAsync(ip + i.ToString() + ":8080/alive");
                    if (responseString.Result == "200")
                    {
                        Servidor s = new Servidor(IPAddress.Parse(ip + i.ToString()), "Servidor " + i.ToString());
                        Servidor.Agregar(s);
                    }
                }
                Actualizar();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

【问题讨论】:

    标签: c#


    【解决方案1】:

    调用GetStringAsync时需要在ip地址前指定HTTP方案(http://或https://)

    例如,

    var responseString = client.GetStringAsync("https://" + ip + i.ToString() + ":8080/alive");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-30
      • 2020-11-22
      • 1970-01-01
      • 2019-01-15
      • 2021-07-30
      • 1970-01-01
      • 2018-10-01
      • 1970-01-01
      相关资源
      最近更新 更多