我尝试在“Microsoft Visual Studio 2017”Xamarin Android App中创建应用程序。
如果我用http而不是(https)重复它可以正常工作
我的问题是:我如何重新启动https电话?
基本代码:
using Android.App;
using Android.Widget;
using Android.OS;
using Android.Support.V7.App;
using System.Net.Http;
using System;
using System.Text;
using System.Net;
using System.IO;
//System.Net.WebException: Error: TrustFailure (The authentication or decryption has failed.)
namespace httprequest
{
[Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
public class MainActivity : AppCompatActivity
{
private static readonly HttpClient client = new HttpClient();
Button btn1;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
if (Build.Brand.Equals("GENERIC", StringComparison.InvariantCultureIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback +=
(sender, cert, chain, sslPolicyErrors) => true;
}
btn1 = FindViewById<Button>(Resource.Id.httpbtn1);
btn1.Click += delegate
{
using (var wb = new WebClient())
{
var request = (HttpWebRequest)WebRequest.Create("https://???");
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
Console.WriteLine(responseString);
}
};
}
}
}
这是我得到的:
未处理的异常:System.Net.WebException:错误:TrustFailure(一个 或者发生了更多错误。)
在高级Adnroid Properites中:
HttpClient实现:Android
SSL / TLS实施:原生TLS 1.2 +
答案 0 :(得分:0)
也许它仍在帮助OP或其他人在此问题上绊脚石: 我想访问我们的公司API,该公司的API使用的是受信任的第三方通过连接到我们的Blackberry Server的Samsung S7(Android 8)颁发的证书。设备本身已安装了必要的证书,但是在我像OP所说的那样切换HTTPS-Implementation之前,我仍然收到“ Trust Failure Exception”(信任失败异常):
右键单击Android项目->设置-> Android选项->高级
将HTTPClient实现更改为Android,将SSL / TLS实现更改为Native TLS 1.2 +
然后我遇到以下错误:
java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
因此,您似乎需要将Android指向自己的证书存储区。为此,请按照下列步骤操作:
在“资源”目录中创建子目录xml
在内部,使用以下内容创建network_security_config.xml
<?xml version="1.0" encoding="utf-8" ?>
<network-security-config>
<base-config>
<trust-anchors>
<!-- Trust preinstalled CAs -->
<certificates src="system" />
<!-- Additionally trust user added CAs -->
<certificates src="user" />
</trust-anchors>
</base-config>
</network-security-config>
打开您的AndroidManifest.xml并将以下属性添加到application-Tag
<application [...] android:networkSecurityConfig="@xml/network_security_config">
就我而言,此后一切都正常运行。