System.Net.Http.HttpClient在[通用Windows平台]不能正常工作

本文关键字:常工作 不能 工作 平台 HttpClient Http Net Windows 通用 System | 更新日期: 2023-09-27 18:13:12

我写了一个简单的方法从(在线)REST服务获取数据:

    public async Task<Object> GetTask()
    {
        try
        {
            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://111.111.111.111:8080/");
                HttpResponseMessage result = await client.GetAsync("ABC/CDE/getsomeinfo");
                if (result.IsSuccessStatusCode)
                {
                    //Deserialize
                }
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine("Error" + ex);
        }
        return null;
    }

每当我在UWP上运行这个时,我都会得到catch异常:

找不到与此错误代码相关的文本。

无法建立与服务器的连接

HResult 2147012867

我试图连接我的客户端与内部网络的restapi。在表单相同的代码工作正常

System.Net.Http.HttpClient在[通用Windows平台]不能正常工作

试试这个

HttpResponseMessage response;
public async Task<string> webserviceResponse(string HttpMethod)
{      
    // check internet connection is available or not   
    if (NetworkInterface.GetIsNetworkAvailable() == true)
    {
       // CancellationTokenSource cts = new CancellationTokenSource(2000); // 2 seconds
        HttpClient client = new HttpClient();
        MultipartFormDataContent mfdc = new MultipartFormDataContent();
        mfdc.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
        string GenrateUrl = "your url";
        if (HttpMethod == "POST")
        {
            response = await client.PostAsync(GenrateUrl, mfdc);
        }
        else if (HttpMethod == "PUT")
        {
            response = await client.PutAsync(GenrateUrl, mfdc);
        }
        else if (HttpMethod == "GET")
        {
            response = await client.GetAsync(GenrateUrl);
        }
        var respon = await response.Content.ReadAsStringAsync();
        string convert_response = respon.ToString();
        return convert_response;
    }
    else
    {
        return "0";
    }
}