ana*_*aid 23 ssl xamarin.forms
有没有办法做这里描述的事情:https://stackoverflow.com/a/2675183但在Xamarin.Forms PCL应用程序?我正在使用HttpClient连接到服务器.
Ale*_*Lau 35
ServicePointManager 未在PCL中定义,但在平台特定类中定义.
有ServicePointManager两个Xamarin.iOS和Xamarin.Android具有相同的使用.您可以在平台项目的任何类中引用它.但是,目前没有这样的类,似乎没有办法为Windows Phone应用程序这样做.
例:
// Xamarin.Android
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
{
protected override void OnCreate(Bundle bundle)
{
// You may use ServicePointManager here
ServicePointManager
.ServerCertificateValidationCallback +=
(sender, cert, chain, sslPolicyErrors) => true;
base.OnCreate(bundle);
global::Xamarin.Forms.Forms.Init(this, bundle);
LoadApplication(new App());
}
}
// Xamarin.iOS
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
ServicePointManager
.ServerCertificateValidationCallback +=
(sender, cert, chain, sslPolicyErrors) => true;
global::Xamarin.Forms.Forms.Init();
LoadApplication(new App());
return base.FinishedLaunching(app, options);
}
}
Run Code Online (Sandbox Code Playgroud)
And*_*tão 17
使用Xamarin.Forms方式的唯一代码,实例化 HttpClientHandler 示例:
private HttpClient _httpClient;
public HttpClient HttplicentAccount
{
get
{
_httpClient = _httpClient ?? new HttpClient
(
new HttpClientHandler()
{
ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) =>
{
//bypass
return true;
},
}
, false
)
{
BaseAddress = new Uri("YOUR_API_BASE_ADDRESS"),
};
// In case you need to send an auth token...
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", "YOUR_TOKEN");
return _httpClient;
}
}
Run Code Online (Sandbox Code Playgroud)
如果您正在使用AndroidClientHandler,则需要提供SSLSocketFactory和 的自定义实现HostnameVerifier并禁用所有检查。为此,您需要子类化AndroidClientHandler并覆盖适当的方法。
internal class BypassHostnameVerifier : Java.Lang.Object, IHostnameVerifier
{
public bool Verify(string hostname, ISSLSession session)
{
return true;
}
}
internal class BypassSslValidationClientHandler : AndroidClientHandler
{
protected override SSLSocketFactory ConfigureCustomSSLSocketFactory(HttpsURLConnection connection)
{
return SSLCertificateSocketFactory.GetInsecure(1000, null);
}
protected override IHostnameVerifier GetSSLHostnameVerifier(HttpsURLConnection connection)
{
return new BypassHostnameVerifier();
}
}
Run Code Online (Sandbox Code Playgroud)
进而
var handler = new BypassSslValidationClientHandler();
var httpClient = new System.Net.Http.HttpClient(handler);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16500 次 |
| 最近记录: |