使用HttpClient时HttpRequestException?

时间:2016-04-14 19:05:31

标签: c# win-universal-app dotnet-httpclient

我有WebClient请求网址。我想在UWP应用程序中做同样的事情,我发现我必须导入Microsoft.Net.Http并使用HttpClient

所以我替换了它(在类库中):

WebClient client = new WebClient();
client.Headers[HttpRequestHeader.UserAgent] = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2";
string content = client.DownloadString(url);

通过这个在PCL库中:

HttpClient client = new HttpClient();
string content = await client.GetStringAsync(url);

现在我遇到了这个例外:

System.Net.Http.HttpRequestException occurred
  HResult=-2147012867
  Message=An error occurred while sending the request.
  Source=System.Net.Http
  StackTrace:
       at System.Net.Http.HttpClientHandler.<SendAsync>d__1.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
       at XXXX.YYYY.MHDJ.ZZZZ.<ParsePage>d__4.MoveNext()
  InnerException: 
       ErrorCode=-2147012867
       HResult=-2147012867
       Message=Le texte associé à ce code d’erreur est introuvable.

Impossible d'établir une connexion avec le serveur

       Source=""
       StackTrace:
            at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
            at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
            at System.Net.Http.HttpHandlerToFilter.<SendAsync>d__1.MoveNext()
         --- End of stack trace from previous location where exception was thrown ---
            at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
            at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
            at System.Net.Http.HttpClientHandler.<SendAsync>d__1.MoveNext()
       InnerException: 

我不认为问题是标题,那是什么?

3 个答案:

答案 0 :(得分:2)

十六进制中的HRESULT代码-21470128670x80072EFD0x8007前缀意味着它实际上是HRESULT wrapper around a Win32 error code。原始Win32错误代码为0x2EFD

Win32 error code list告诉我们,0x2EE00x2F8F的值是ERROR_INTERNET_*错误代码,这听起来像是错误的错误。在点击指向Win32 ERROR_INTERNET_* error code listing的链接后,我们可以将错误代码0x2EFD转换回小数(12029)并发现错误ERROR_INTERNET_CANNOT_CONNECT

  

尝试连接服务器失败。

相当通用,并没有多大帮助。

我建议您再次尝试连接,确保您的应用程序具有适当的权限,并且该设备实际上具有可用的Internet连接。如果这不起作用,请尝试重新添加UserAgent标头;您设备上的网络堆栈可能会坚持使用它。

更新:追踪错误代码含义相当繁琐,所以我wrote an app to do it

答案 1 :(得分:1)

遇到了0x80072efd问题。如果不是几天解决,我花了几个小时。对我有用的解决方案是来自管理命令提示符的以下命令:

netsh winhttp reset proxy

答案 2 :(得分:0)

有很多方法可以做,而且我并不是说这是最好的方法,但这就是我构建方法的方法。我用这个例子来返回以JSON格式提供的美国州对象列表。一个重要的注意事项......这是在通用Windows类库中,而不是PCL ...但我不认为它使用了PCL无法访问的任何内容。

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using System.Threading.Tasks;

//IStateInfo is my model class interface
public async Task<IList<IStateInfo>> GetAllStatesAsync()
{
    List<IStateInfo> states = new List<IStateInfo>();
    try
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://YourBaseApiHere");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            string url = "lookup/usstates";
            HttpResponseMessage response = await client.GetAsync(url);
            if (response.IsSuccessStatusCode)
            {
                var json = await response.Content.ReadAsStringAsync();
                //deserialize into client class Newtonsoft JSON used here
                var lst = JsonConvert.DeserializeObject<List<StateInfo>>(json);
                states.AddRange(lst);
            }
            else
            {
                //notify of failed web call here
            }
        }
    }
    catch (Exception e)
    {
        //notify of error
    }
    return states;
}