【问题标题】:HttpClient not connecting to URL from UWP appHttpClient 未从 UWP 应用程序连接到 URL
【发布时间】:2019-05-21 08:31:24
【问题描述】:

首先,我必须承认我不确定我应该使用 Windows.Web.Http.HttpClient 还是 System.Net.Http.HttpClient。似乎 Windows.Web.Http.HttpClient 是 UWP 的必经之路,但我都尝试过,但都没有成功。

我希望从 URL 收到一个 JSON 对象。当我将 URL 复制并粘贴到浏览器中时,我可以很好地看到 JSON 对象。如果我在连接浏览器后不理会缓存,则 UWP 从缓存中读取没有问题。我使用相同的代码连接到https://jsonplaceholder.typicode.com/todos/1,并且能够从那里检索 JSON 对象而没有任何问题。这是我的基本尝试:

async void Connect()
    {
        using (Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient())
        {
            Uri uri = new Uri(@"https://www.nottheactualdomainname.com/?api=software-api&email=xxxx@xxxx.com&licence_key=xxxx&request=status&product_id=xxxxinstance=20181218215300");
            Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage();
            string httpResponseBody = "";

            try
            {
                httpResponse = await httpClient.GetAsync(uri);
                httpResponse.EnsureSuccessStatusCode();

                httpResponseBody = await httpResponse.Content.ReadAsStringAsync();

                if (JsonObject.TryParse(httpResponseBody, out JsonObject keyValuePairs))
                {
                    //handle JSON object
                }
                else
                {
                    //didn't recieve JSON object
                }

            }
            catch (Exception ex)
            {
                httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message;
            }
        }
    }

我已经尝试在不同的点包含这个(即在 using 语句之前,在初始化 httpResponse 之前,以及在 try 语句之前):

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

除此之外(知道我只能在调试时这样做):

//for debugging ONLY; not safe for production
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

有时我会收到此错误:

错误:80131500 消息:响应状态码不表示成功:403 ()。

有时我会收到此错误:

错误:80190193 消息:禁止 (403)。

或两者兼而有之。我在 Windows.Web.Http.HttpClient 和 System.Net.Http.HttpClient 都试过这个。

我最终需要确保我的 URL 包含服务器的适当凭据。但是,不正确的凭据应该只返回带有错误信息的 JSON,而我没有得到。我可以连接到https://www.nottheactualdomainname.com。接下来我应该检查什么?

【问题讨论】:

    标签: c# uwp dotnet-httpclient


    【解决方案1】:

    我找到了答案here

    我能够使用浏览器开发人员工具查看请求标头。然后我添加了这个:

    httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36");
    

    【讨论】:

      猜你喜欢
      • 2019-11-21
      • 2019-07-19
      • 2013-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-28
      • 1970-01-01
      • 2015-12-29
      相关资源
      最近更新 更多