【问题标题】:Xamarin Android PCL Web Request HangsXamarin Android PCL Web 请求挂起
【发布时间】:2017-03-31 20:58:57
【问题描述】:

我正在尝试制作一个可以为 Xamarin Android 项目发出 Web 请求的 PCL。

我的 AndoridManifest.xml 如下所示

<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="JJJ.Mobile.Android" android:installLocation="auto">
    <uses-sdk android:minSdkVersion="19" android:targetSdkVersion="23" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <application android:allowBackup="true" android:label="@string/app_name" android:theme="@style/MyTheme"></application>
</manifest>

Android主活动按钮click中的代码只是直接调用了这个PCL Create方法。

我在执行 SendAsync 和返回 null 的行上有断点,SendAsync 断点被击中,当您跨过它时 VS 挂起一秒钟,然后显示模拟器并且应用程序挂起 - Android 显示在之后不久关于不响应等待或不响应的消息 - 异常断点永远不会被命中。控制台不显示异常

public async Task<HttpResponseMessage> Create()
        {
            try
            {
                var uri = new Uri("http://rxnav.nlm.nih.gov/REST/RxTerms/rxcui/198440/allinfo");

                var httpClient = new HttpClient();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, uri);

                var response = await httpClient.SendAsync(request);
                return response;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

点击按钮后的控制台输出,不确定是否有用

Thread started:  #6
03-30 19:31:17.669 D/Mono    ( 2556): Assembly Ref addref System.Net.Http[0x9d63d4e0] -> System.Core[0x9e0abbe0]: 10
Thread started: <Thread Pool> #7
03-30 19:31:18.392 D/Mono    ( 2556): [0x9d7bf930] hill climbing, change max number of threads 3
Thread started: <Thread Pool> #8
03-30 19:31:18.490 D/Mono    ( 2556): [0x9adbf930] worker starting
03-30 19:31:18.538 D/Mono    ( 2556): Unloading image System.dll [0x9ae04f00].
03-30 19:31:18.539 D/Mono    ( 2556): Image addref System[0xaed95740] -> System.dll[0xaadd4900]: 5
03-30 19:31:18.539 D/Mono    ( 2556): Config attempting to parse: 'System.dll.config'.
03-30 19:31:18.539 D/Mono    ( 2556): Config attempting to parse: '/Users/builder/data/lanes/4009/3a62f1ea/source/monodroid/builds/install/mono-x86/etc/mono/assemblies/System/System.config'.
03-30 19:31:18.540 D/Mono    ( 2556): Unloading image System.dll [0x9ae04f00].
03-30 19:31:18.540 D/Mono    ( 2556): Image addref System[0xaed95920] -> System.dll[0xaadd4900]: 6
03-30 19:31:18.541 D/Mono    ( 2556): Config attempting to parse: 'System.dll.config'.
03-30 19:31:18.541 D/Mono    ( 2556): Config attempting to parse: '/Users/builder/data/lanes/4009/3a62f1ea/source/monodroid/builds/install/mono-x86/etc/mono/assemblies/System/System.config'.
03-30 19:31:18.543 D/Mono    ( 2556): Unloading image System.dll [0x9ae04f00].
03-30 19:31:18.543 D/Mono    ( 2556): Image addref System[0xaed95920] -> System.dll[0xaadd4900]: 7
03-30 19:31:18.543 D/Mono    ( 2556): Config attempting to parse: 'System.dll.config'.
03-30 19:31:18.543 D/Mono    ( 2556): Config attempting to parse: '/Users/builder/data/lanes/4009/3a62f1ea/source/monodroid/builds/install/mono-x86/etc/mono/assemblies/System/System.config'.
03-30 19:31:18.545 D/Mono    ( 2556): Unloading image System.dll [0x9ae04f00].
03-30 19:31:18.545 D/Mono    ( 2556): Image addref System[0xaed95920] -> System.dll[0xaadd4900]: 8
03-30 19:31:18.545 D/Mono    ( 2556): Config attempting to parse: 'System.dll.config'.
03-30 19:31:18.545 D/Mono    ( 2556): Config attempting to parse: '/Users/builder/data/lanes/4009/3a62f1ea/source/monodroid/builds/install/mono-x86/etc/mono/assemblies/System/System.config'.
03-30 19:31:18.573 D/Mono    ( 2556): DllImport searching in: '__Internal' ('(null)').
03-30 19:31:18.573 D/Mono    ( 2556): Searching for 'java_interop_jnienv_is_assignable_from'.
03-30 19:31:18.573 D/Mono    ( 2556): Probing 'java_interop_jnienv_is_assignable_from'.
03-30 19:31:18.573 D/Mono    ( 2556): Found as 'java_interop_jnienv_is_assignable_from'.
03-30 19:31:18.574 D/Mono    ( 2556): DllImport searching in: '__Internal' ('(null)').
03-30 19:31:18.574 D/Mono    ( 2556): Searching for 'java_interop_jnienv_get_byte_array_region'.
03-30 19:31:18.574 D/Mono    ( 2556): Probing 'java_interop_jnienv_get_byte_array_region'.
03-30 19:31:18.574 D/Mono    ( 2556): Found as 'java_interop_jnienv_get_byte_array_region'.
03-30 19:31:18.575 D/Mono    ( 2556): DllImport searching in: '__Internal' ('(null)').
03-30 19:31:18.575 D/Mono    ( 2556): Searching for 'java_interop_jnienv_set_byte_array_region'.
03-30 19:31:18.575 D/Mono    ( 2556): Probing 'java_interop_jnienv_set_byte_array_region'.
03-30 19:31:18.575 D/Mono    ( 2556): Found as 'java_interop_jnienv_set_byte_array_region'.
03-30 19:31:18.632 W/Mono    ( 2556): The request to load the assembly System.Core v4.0.0.0 was remapped to v2.0.5.0
03-30 19:31:18.632 D/Mono    ( 2556): Unloading image System.Core.dll [0x9ae06d00].
03-30 19:31:18.632 D/Mono    ( 2556): Image addref System.Core[0xaed96460] -> System.Core.dll[0xaadd6700]: 5
03-30 19:31:18.632 D/Mono    ( 2556): Config attempting to parse: 'System.Core.dll.config'.
03-30 19:31:18.632 D/Mono    ( 2556): Config attempting to parse: '/Users/builder/data/lanes/4009/3a62f1ea/source/monodroid/builds/install/mono-x86/etc/mono/assemblies/System.Core/System.Core.config'.
03-30 19:31:18.640 W/Mono    ( 2556): The request to load the assembly System.Core v4.0.0.0 was remapped to v2.0.5.0
03-30 19:31:18.641 D/Mono    ( 2556): Unloading image System.Core.dll [0x9ae05e00].
03-30 19:31:18.641 D/Mono    ( 2556): Image addref System.Core[0xaed96460] -> System.Core.dll[0xaadd6700]: 6
03-30 19:31:18.641 D/Mono    ( 2556): Config attempting to parse: 'System.Core.dll.config'.
03-30 19:31:18.641 D/Mono    ( 2556): Config attempting to parse: '/Users/builder/data/lanes/4009/3a62f1ea/source/monodroid/builds/install/mono-x86/etc/mono/assemblies/System.Core/System.Core.config'.
03-30 19:31:18.895 D/Mono    ( 2556): [0x9d7bf930] hill climbing, change max number of threads 2
03-30 19:31:24.114 D/Mono    ( 2556): [0x9adbf930] worker finishing
Thread finished: <Thread Pool> #8
The thread 'Unknown' (0x8) has exited with code 0 (0x0).

模拟器运行的是 Android 6,我使用内置浏览器检查了互联网,它可以工作。我对此感到非常困惑,任何帮助将不胜感激!

【问题讨论】:

    标签: android xamarin.android


    【解决方案1】:

    我假设您的内存不足,这会迫使您的任务终止。我使用了下面的代码,一切都按预期工作。我将项目设置为 Xamarin.Android 项目,其中 Xamarin.PCL 用于请求部分。我还创建了一个模拟模型,以更简洁的方式获得响应。我真的不知道你在用 XML 做什么,所以如果它不相关,你可以省略那部分。

    项目设置

    安装在 PCL 中的 Nuget 包

    现代HttpClient
    Newtonsoft.Json

    主要活动
    以下是 Android 主活动

    using Android.App;
    using Android.OS;
    using XamPCL;
    
    namespace App1
    {
        [Activity(Label = "App1", MainLauncher = true, Icon = "@drawable/icon")]
        public class MainActivity : Activity
        {
            protected override async void OnCreate(Bundle bundle)
            {
                base.OnCreate(bundle);
    
                // Set our view from the "main" layout resource
                SetContentView(Resource.Layout.Main);
    
                    var n = new XamPCLa();
                    //you want to await this function. 
                    Model response = await n.Test();
            }
        }
    }
    

    Xamarin.Portable (XamPCL)

    using ModernHttpClient;
    using Newtonsoft.Json;
    using System;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Threading.Tasks;
    
    
    namespace XamPCL
    {
        public class Model
        {
            /// <summary>
            /// this will resolve your xml into the model
            /// </summary>
            [JsonProperty(PropertyName = "rxtermsProperties")]
            public DrugSpec Container {get;set;}
        }
    
        public class DrugSpec
        {
            /// <summary>
            /// 
            /// </summary>
            [JsonProperty(PropertyName = "displayName")]
            public string DisplayName { get; set; }
        }
    
        public class XamPCLa
        {
            public XamPCLa()
            {
    
            }
    
            public async Task<Model> Test()
            {
                var httpClient = GetHttpClient();
                try
                {
                    var response = await httpClient.GetAsync(@"https://rxnav.nlm.nih.gov/REST/RxTerms/rxcui/198440/allinfo").ConfigureAwait(false);
                    response.EnsureSuccessStatusCode();
    
                    if (response.IsSuccessStatusCode)
                    {
                        var content = response.Content;
    
                        string jsonString = await content.ReadAsStringAsync().ConfigureAwait(false);
    
                        return JsonConvert.DeserializeObject<Model>(jsonString);
                    }
                }
                catch (Exception e)
                {
    
                }
                return new Model();
            }
    
    
            private HttpClient GetHttpClient()
            {
                var httpClient = new HttpClient(new NativeMessageHandler());
    
                httpClient.DefaultRequestHeaders.Accept.Clear();
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
                return httpClient;
            }
        }
    }
    

    MainActivity 中的结果

    【讨论】:

      【解决方案2】:

      不确定是什么原因造成的。但是,我可以向我的 Web 服务发出 GET 请求。我改用WebRequest。我会提供下面的代码,你可以试试。

      public async Task<WebResponse> Create()
      {
          var uri = "http://rxnav.nlm.nih.gov/REST/RxTerms/rxcui/198440/allinfo";
          WebRequest request = WebRequest.CreateHttp(uri);
          string responseValue = null;
          try
          {
              using (var response = await request.GetResponseAsync())
              {
                  using (var stream = response.GetResponseStream())
                  {
                      if (stream != null)
                      {
                          using (var reader = new StreamReader(stream))
                          {
                              responseValue = await reader.ReadToEndAsync();
                          }
                      }
                  }
              }
              return responseValue;
          }
          catch (Exception ex)
          {
              return null;
          }
      }
      

      希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-09-08
        • 2016-08-09
        • 2012-07-04
        • 2014-01-14
        • 1970-01-01
        • 2022-12-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多