如何为HttpClient构建合法的URL

时间:2018-07-04 14:04:41

标签: c# httpclient

下面的代码似乎无法正常工作,我不确定如何为HttpClient构建包含撇号,方括号和其他符号的网址字符串

   string myUrl ="Http://XXXXX.net/Cust('10008')/AcctDetail

    string strUrl = System.Net.WebUtility.UrlEncode(myUrl);
    var client = new System.Net.Http.HttpClient();
    client.DefaultRequestHeaders.Accept.Clear();         
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", "swerefeqeaQw=");

    var response = await client.GetAsync(strUrl);            

    string status = response.StatusCode.ToString();


    Problem: at var response = await client.GetAsync(strUrl);  

System.InvalidOperationException: The request URI must either be an absolute URI or BaseAddress must be set

如何为HttpClient构建这样的url字符串?我正在使用HttpClien消耗OData Web服务,但我发现URL要求是diff。此Httpclient用于Xamarin(Microsoft移动跨平台)

谢谢

1 个答案:

答案 0 :(得分:-2)

如果服务器是标准REST,则URL应该是

string myUrl = "http://XXXXX.net/Cust/10008/AcctDetail";