【问题标题】:Getting a JSON from remote url in Visual Studio Xamarin is not working从 Visual Studio Xamarin 中的远程 url 获取 JSON 不起作用
【发布时间】:2017-05-30 01:42:11
【问题描述】:

我开始学习 Xamarin 以开发适用于 iOS、Android 和 Windows Phone 的应用程序。

似乎是一个简单的问题,但我不知道如何继续使用 Xamarin。

我有以下几行代码:

public async Task<List<MyData>> GetItemsAsync()
{
        HttpClient client = new HttpClient();
        try {
            string result = await client.GetStringAsync( "https://jsonplaceholder.typicode.com/posts/1" );
            if(!string.IsNullOrWhiteSpace(result)) {
            }
        } catch( Exception ex ) {
            return await Task.FromResult(new List<MyData>(0));
        } finally {
            client.Dispose(); //of course, I can use `using`
        }

        return await Task.FromResult(new List<MyData>(0));
}

在 Visual Studio Android Emulator(VisualStudio_android-23_x86_phone (Android 6.0 - API 23)) 中调试时,string result 开头的行卡住了,没有任何反应,也没有抛出异常。我无法在 Visual Studio 中使用 F10 进行检查。

另外,我不能使用WebClient,因为 System.Net 不包含它。

编辑:如果我删除 await,那么我会收到一般异常:

我的错误在哪里?

【问题讨论】:

  • 您确定您的 URI 可以从您的设备/模拟器访问吗?您是否等待查看请求最终是否超时?
  • 是的,我自己试过了,它在Browser浏览器中相应显示。
  • 我看到是 HTTPS 的问题,如果我使用 http 会正常工作...如何解决 https 问题?
  • 聚合异常的内部异常是什么?
  • Error: SecureChannelFailure (The authentication or decryption has failed.)

标签: c# visual-studio xamarin


【解决方案1】:

对于那些遇到错误的人: Error: SecureChannelFailure (The authentication or decryption has failed.)

请使用适用于 Android 的特定处理程序:

using (HttpClient myClient = new HttpClient(new AndroidClientHandler())) { }

或者对于 iOS:

using(HttpClient myClient = new HttpClient(new CFNetworkHandler())) {}

参考资料:

https://developer.xamarin.com/guides/cross-platform/macios/http-stack/ https://developer.xamarin.com/guides/android/application_fundamentals/http-stack/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-09
    • 1970-01-01
    • 2017-02-02
    • 2018-04-02
    • 1970-01-01
    • 2020-09-15
    相关资源
    最近更新 更多