如何解决'提供了无效的请求URI。请求URI必须是绝对URI或必须设置BaseAddress”

时间:2019-09-05 01:12:12

标签: c#

当我尝试使用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);
            }

1 个答案:

答案 0 :(得分:2)

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

例如,

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