gpt4 book ai didi

c# - 如何使用 WebView 在 Xamarin C# 应用程序中为 Android 设置代理?

转载 作者:太空宇宙 更新时间:2023-11-03 12:14:57 26 4
gpt4 key购买 nike

我有一个使用 Xamarin 在 C# 中创建的 Android 应用程序。

这本质上是一个具有一些附加功能的网络浏览器,现在我想添加一个选项来设置要使用的代理。在应用程序中,我使用 WebView 连接到网站。

我尝试从该主题(How can I set ProxySettings and ProxyProperties on Android Wi-Fi connection using Java?)中实现解决方案,但 WifiConfiguration 中没有 linkProperties。这是它的样子:

private static Java.Lang.Object getField(Java.Lang.Object obj, String name)
{
Field f = obj.Class.GetField(name);
Java.Lang.Object o = f.Get(obj);
return o;
}

public void SetHttpProxy(string proxyServerAddress, int proxyServerInt)
{
try
{
var wifiManager = context.GetSystemService(Context.WifiService) as WifiManager;
if (!wifiManager.IsWifiEnabled)
return;

var configurationList = wifiManager.ConfiguredNetworks;

var cur = wifiManager.ConnectionInfo.NetworkId;
var configuration = configurationList.FirstOrDefault(conf => conf.NetworkId == cur);

getField(configuration, "linkProperties");

}
catch (Exception e)
{
throw;
}
}

最佳答案

这是适用于 4.、5.、6.* 和 7.* Android 操作系统版本的解决方案:

public static void SetProxy(WebView webView, string host, int port, bool bypass)
{
Context appContext = webView.Context.ApplicationContext;
JavaSystem.SetProperty("http.proxyHost", host);
JavaSystem.SetProperty("http.proxyPort", port + "");
JavaSystem.SetProperty("https.proxyHost", host);
JavaSystem.SetProperty("https.proxyPort", port + "");
if (bypass)
JavaSystem.SetProperty("http.nonProxyHosts", BYPASS_PATTERN);

try
{
Class applictionCls = Class.ForName(APPLICATION_CLASS_NAME);
Field loadedApkField = applictionCls.GetField("mLoadedApk");
loadedApkField.Accessible = true;
Object loadedApk = loadedApkField.Get(appContext);
Class loadedApkCls = Class.ForName("android.app.LoadedApk");
Field receiversField = loadedApkCls.GetDeclaredField("mReceivers");
receiversField.Accessible = true;
ArrayMap receivers = (ArrayMap) receiversField.Get(loadedApk);
foreach (Object receiverMap in receivers.Values())
{
foreach (Object rec in Extensions.JavaCast<ArrayMap>(receiverMap).KeySet())
{
Class clazz = rec.Class;
if (clazz.Name.Contains("ProxyChangeListener"))
{
Method onReceiveMethod = clazz.GetDeclaredMethod("onReceive", Class.FromType(typeof(Context)), Class.FromType(typeof(Intent)));
Intent intent = new Intent(Android.Net.Proxy.ProxyChangeAction);

onReceiveMethod.Invoke(rec, appContext, intent);
}
}
}
}
catch (Exception)
{
}
}

关于c# - 如何使用 WebView 在 Xamarin C# 应用程序中为 Android 设置代理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50230106/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com