2017-05-31 174 views
0

是否可以执行HTTP请求并获取Xamarin中的响应主体?因为我从他们的文档中尝试了很多代码示例,并且它不适用于我的Android设备,但有一个例外说:NameResolutionFailure。如何修复Xamarin WebClient错误NameResolutionFailure?

我的代码是:

 Uri uri = new Uri("http://www.google.com"); 
     string ret = "ERROR"; 
     try 
     { 
      using (WebClient webClient = new WebClient()) 
      { 
       //You can set webClient.Headers there 
       webClient.Encoding = System.Text.Encoding.UTF8; 
       ret = webClient.DownloadString(uri); 
       Console.WriteLine("Data: " + ret); 
      } 
     } 
     catch (Exception ex) 
     { 
      ret = ex.Message; 
      Console.WriteLine("Error: " + ret); 
     } 

我发现这个错误时,你在做通过WIFI请求,但seriousely occures?

所有的肮脏的解决方案,如“用IP地址替换主机名”不起作用,我是Xamarin的新手,我对它有不好的印象。

+0

难道ü尝试使用Newtonsoft.Json。 –

+0

不,如何使用?或链接? –

+0

哦,这是一个第三方图书馆?但为什么xamarin没有本地解决方案呢? –

回答

0

我写一个简单的例子,如何使用Newtonsoft.Json获取数据:

public static async Task<Details> getDetails(string authKey, string AppVersionandBuild) 
{ 

    var response = await JsonWebCall<Details>.GetDirect(
     JsonWebCall<object>.baseURl + "MyApp/GetDetails", 
     authKey, 
     AppVersionandBuild); 

    return response.Item1; 
} 

这是我JsonWebCall类

public class JsonWebCall<T> 
{ 
    public static string baseURl = "http://YourServiceURL/"; 

    /// <summary> 
    /// Gets the client. 
    /// </summary> 
    /// <returns></returns> 
    public static HttpClient GetClient() 
    { 
     var timeout = new TimeSpan(0, 10, 0); 
     var client = new HttpClient(new ModernHttpClient.NativeMessageHandler()); 
     // Due to a bug in Xamarin's HttpClient, this value MUST exceed the timeout of the native http client. 
     // The REAL timeout will be the native http client's timeout which will properly throw the timeout exception. 
     client.Timeout = timeout.Add(new TimeSpan(0, 1, 0)); 
     return client; 
    } 

    /// <summary> 
    /// Gets the message. 
    /// </summary> 
    /// <param name="method">The method.</param> 
    /// <param name="url">The URL.</param> 
    /// <param name="authkey">The authkey.</param> 
    /// <param name="Manufacturer">The manufacturer.</param> 
    /// <param name="Model">The model.</param> 
    /// <param name="OS">The os.</param> 
    /// <param name="OSVersion">The os version.</param> 
    /// <param name="UniqueIdentifier">The unique identifier.</param> 
    /// <param name="AppVersionandBuild">The application versionand build.</param> 
    /// <returns></returns> 
    public static HttpRequestMessage GetMessage(HttpMethod method, string url, string authkey, string Manufacturer, string Model, string OS, string OSVersion, string UniqueIdentifier, string AppVersionandBuild) 
    { 
     var message = new HttpRequestMessage(method, url); 

     if (!string.IsNullOrWhiteSpace(authkey)) 
      message.Headers.Add("X-AUTH-KEY", new List<string>() { authkey }); 
     if (!string.IsNullOrWhiteSpace(UniqueIdentifier)) 
      message.Headers.Add("X-DEVICE-ID", new List<string>() { UniqueIdentifier }); 
     if (!string.IsNullOrWhiteSpace(Model)) 
      message.Headers.Add("X-DEVICE-MODEL", new List<string>() { Model }); 
     if (!string.IsNullOrWhiteSpace(Manufacturer)) 
      message.Headers.Add("X-DEVICE-MFG", new List<string>() { Manufacturer }); 
     if (!string.IsNullOrWhiteSpace(OSVersion)) 
      message.Headers.Add("X-OS-VERSION", new List<string>() { OSVersion }); 
     if (!string.IsNullOrWhiteSpace(OS)) 
      message.Headers.Add("X-OS-NAME", new List<string>() { OS }); 
     if (!string.IsNullOrWhiteSpace(AppVersionandBuild)) 
      message.Headers.Add("X-APP-VERSION", new List<string>() { AppVersionandBuild }); 
     return message; 
    } 
    /// <summary> 
    /// Get data that is not encapulated in an odata call 
    /// </summary> 
    /// <param name="url">the url of the service action</param> 
    /// <param name="authkey">The authentication key required y the server</param> 
    /// <param name="DeviceID">the device id of the device making this service call</param> 
    /// <returns></returns> 
    public async static Task<Tuple<T>> Get(string url, string authKey, string Manufacturer, string Model, string OS, string OSVersion, string UniqueIdentifier, string AppVersionandBuild) 
    { 
     var client = GetClient(); 
     var req = GetMessage(HttpMethod.Get, url, authKey, Manufacturer, Model, OS, OSVersion, UniqueIdentifier, AppVersionandBuild); 
     var response = await client.SendAsync(req).ConfigureAwait(false); 
     T returnedObject = default(T); 
     returnedObject = JsonConvert.DeserializeObject<T>(await response.Content.ReadAsStringAsync().ConfigureAwait(false)); 

     return new Tuple<T>(returnedObject); 
    } 
    /// <summary> 
    /// Gets the request. 
    /// </summary> 
    /// <param name="method">The method.</param> 
    /// <param name="url">The URL.</param> 
    /// <param name="authkey">The authkey.</param> 
    /// <param name="AppVersionandBuild">The application versionand build.</param> 
    /// <returns></returns> 
    public static HttpRequestMessage GetRequest(HttpMethod method, string url, string authkey, string AppVersionandBuild) 
    { 
     var message = new HttpRequestMessage(method, url); 

     if (!string.IsNullOrWhiteSpace(authkey)) 
      message.Headers.Add("X-AUTH-KEY", new List<string>() { authkey }); 
     if (!string.IsNullOrWhiteSpace(AppVersionandBuild)) 
      message.Headers.Add("X-APP-VERSION", new List<string>() { AppVersionandBuild }); 
     return message; 
    } 

    /// <summary> 
    /// Gets the direct. 
    /// </summary> 
    /// <param name="url">The URL.</param> 
    /// <param name="authKey">The authentication key.</param> 
    /// <param name="AppVersionandBuild">The application versionand build.</param> 
    /// <returns></returns> 
    public async static Task<Tuple<T>> GetDirect(string url, string authKey, string AppVersionandBuild) 
    { 
     var client = GetClient(); 
     var req = GetRequest(HttpMethod.Get, url, authKey, AppVersionandBuild); 
     var response = await client.SendAsync(req).ConfigureAwait(false); 
     T returnedObject = default(T); 
     var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false); 
     returnedObject = JsonConvert.DeserializeObject<T>(result); 
     return new Tuple<T>(returnedObject); 
    } 
} 
+0

我会尝试它,并回到你,谢谢,顺便说一句,我应该如何导入Visual Studio中的Newtonsoft.Json? –

+0

btw什么是AppVersionandBuild和authKey?为什么做一个简单的HTTP请求太复杂了? –

+1

这些都是强制性的,如果您升级到新版本,那么您可能必须支持使用旧版本的用户。在这种情况下,您必须传递应用程序版本,内部版本等,以便根据用户使用的版本使您的请求具有唯一性。 –