.net core 从(本地)服务器获取APK文件并解析APK信息

简介: ## 1、apk解析除了使用客户端利用aapt.exe、unzip.exe开发客户端解析外,还可以直接利用服务进行解析```csharp/// <summary>/// 从本地服务器获取APK文件并解析APK信息/// </summary>/// <param name="fileName">APK文件的完整路径</param>/// <returns></returns>[HttpPost, HttpGet, HttpOptions, CorsOptions]public IActionResult DecodeAPK(string fileName){ if(fi

2000元阿里云代金券免费领取,2核4G云服务器仅664元/3年,新老用户都有优惠,立即抢购>>>


阿里云采购季(云主机223元/3年)活动入口:请点击进入>>>,


阿里云学生服务器(9.5元/月)购买入口:请点击进入>>>,

1、apk解析除了使用客户端利用aapt.exe、unzip.exe开发客户端解析外,还可以直接利用服务进行解析

/// <summary>
/// 从本地服务器获取APK文件并解析APK信息
/// </summary>
/// <param name="fileName">APK文件的完整路径</param>
/// <returns></returns>
[HttpPost, HttpGet, HttpOptions, CorsOptions]
public IActionResult DecodeAPK(string fileName)
{
   
   
    if(fileName.IndexOf(".apk") == -1 && fileName.IndexOf(".zip") == -1)
    {
   
   
        return ErrorResult("未获取到APP上传路径!", 111111);
    }
    // 从服务器取文件
    if(!string.IsNullOrWhiteSpace(fileName))
    {
   
   
        fileName = fileName.Replace(@"\", @" / ");
        ApkInfo apk = new ApkInfo();
        // 处理apk信息
        try
            apk = ReadAPK.ReadApkFromPath(fileName);
        catch(Exception ex)
            return ErrorResult("APP上传失败!--> APK解析失败,失败原因为:" + ex.Message, 111150);
        return SuccessResult(apk, "APK解析成功");
    }
    else
        return ErrorResult("APP上传失败!--> 从服务器获取APK文件失败,请联系网站管理员!", 111151);
}

2、ReadAPK APK解析帮助类

/// <summary>
/// 读取APK信息
/// </summary>
public class ReadAPK
{
   
   
    /// <summary>
    /// 从上传apk的路径读取并解析apk信息
    /// </summary>
    /// <param name="path"></param>
    /// <returns></returns>
    public static ApkInfo ReadApkFromPath(string path)
    {
   
   
        byte[] manifestData = null;
        byte[] resourcesData = null;
        var manifest = "AndroidManifest.xml";
        var resources = "resources.arsc";
        //读取apk,通过解压的方式读取
        using(var zip = ZipFile.Read(path))
        {
   
   
            using(Stream zipstream = zip[manifest].OpenReader())
            {
   
   
                //将解压出来的文件保存到一个路径(必须这样)
                using(var fileStream = File.Create(manifest, (int) zipstream.Length))
                {
   
   
                    manifestData = new byte[zipstream.Length];
                    zipstream.Read(manifestData, 0, manifestData.Length);
                    fileStream.Write(manifestData, 0, manifestData.Length);
                }
            }
            using(Stream zipstream = zip[resources].OpenReader())
            {
   
   
                //将解压出来的文件保存到一个路径(必须这样)
                using(var fileStream = File.Create(resources, (int) zipstream.Length))
                {
   
   
                    resourcesData = new byte[zipstream.Length];
                    zipstream.Read(resourcesData, 0, resourcesData.Length);
                    fileStream.Write(resourcesData, 0, resourcesData.Length);
                }
            }
        }
        ApkReader apkReader = new ApkReader();
        ApkInfo info = apkReader.extractInfo(manifestData, resourcesData);
        return info;
    }
}

3、APK解析类

注:此段代码解析APK时,若APK包含中文会极其的卡顿,建议上传前先用Npinyin重命名再次上传,至于原因已提交GitHub,暂未得到回复,所以先自己重命名再上传吧
Wrong Local header signature: 0xFF8
image.png

public class ApkReader
{
   
   
    private static int VER_ID = 0;
    private static int ICN_ID = 1;
    private static int LABEL_ID = 2;
    String[] VER_ICN = new String[3];
    String[] TAGS = {
   
   
        "manifest", "application", "activity"
    };
    String[] ATTRS = {
   
   
        "android:", "a:", "activity:", "_:"
    };
    Dictionary < String, object > entryList = new Dictionary < String, object > ();
    List < String > tmpFiles = new List < String > ();
    public String fuzzFindInDocument(XmlDocument doc, String tag, String attr)
    {
   
   
        foreach(String t in TAGS)
        {
   
   
            XmlNodeList nodelist = doc.GetElementsByTagName(t);
            for(int i = 0; i < nodelist.Count; i++)
            {
   
   
                XmlNode element = (XmlNode) nodelist.Item(i);
                if(element.NodeType == XmlNodeType.Element)
                {
   
   
                    XmlAttributeCollection map = element.Attributes;
                    for(int j = 0; j < map.Count; j++)
                    {
   
   
                        XmlNode element2 = map.Item(j);
                        if(element2.Name.EndsWith(attr))
                        {
   
   
                            return element2.Value;
                        }
                    }
                }
            }
        }
        return null;
    }
    private XmlDocument initDoc(String xml)
    {
   
   
        XmlDocument retval = new XmlDocument();
        retval.LoadXml(xml);
        retval.DocumentElement.Normalize();
        return retval;
    }
    private void extractPermissions(ApkInfo info, XmlDocument doc)
    {
   
   
        ExtractPermission(info, doc, "uses-permission", "name");
        ExtractPermission(info, doc, "permission-group", "name");
        ExtractPermission(info, doc, "service", "permission");
        ExtractPermission(info, doc, "provider", "permission");
        ExtractPermission(info, doc, "activity", "permission");
    }
    private bool readBoolean(XmlDocument doc, String tag, String attribute)
    {
   
   
        String str = FindInDocument(doc, tag, attribute);
        bool ret = false;
        try
        {
   
   
            ret = Convert.ToBoolean(str);
        }
        catch
        {
   
   
            ret = false;
        }
        return ret;
    }
    private void extractSupportScreens(ApkInfo info, XmlDocument doc)
    {
   
   
        info.supportSmallScreens = readBoolean(doc, "supports-screens", "android:smallScreens");
        info.supportNormalScreens = readBoolean(doc, "supports-screens", "android:normalScreens");
        info.supportLargeScreens = readBoolean(doc, "supports-screens", "android:largeScreens");
        if(info.supportSmallScreens || info.supportNormalScreens || info.supportLargeScreens) info.supportAnyDensity = false;
    }
    public ApkInfo extractInfo(byte[] manifest_xml, byte[] resources_arsx)
    {
   
   
        string manifestXml = string.Empty;
        APKManifest manifest = new APKManifest();
        try
        {
   
   
            manifestXml = manifest.ReadManifestFileIntoXml(manifest_xml);
        }
        catch(Exception ex)
        {
   
   
            throw ex;
        }
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(manifestXml);
        return extractInfo(doc, resources_arsx);
    }
    public ApkInfo extractInfo(XmlDocument manifestXml, byte[] resources_arsx)
    {
   
   
        ApkInfo info = new ApkInfo();
        VER_ICN[VER_ID] = "";
        VER_ICN[ICN_ID] = "";
        VER_ICN[LABEL_ID] = "";
        try
        {
   
   
            XmlDocument doc = manifestXml;
            if(doc == null) throw new Exception("Document initialize failed");
            info.resourcesFileName = "resources.arsx";
            info.resourcesFileBytes = resources_arsx;
            // Fill up the permission field  不需要返回,注释
            //extractPermissions(info, doc);
            // Fill up some basic fields
            info.minSdkVersion = FindInDocument(doc, "uses-sdk", "minSdkVersion");
            info.targetSdkVersion = FindInDocument(doc, "uses-sdk", "targetSdkVersion");
            info.versionCode = FindInDocument(doc, "manifest", "versionCode");
            info.versionName = FindInDocument(doc, "manifest", "versionName");
            info.packageName = FindInDocument(doc, "manifest", "package");
            int labelID;
            info.label = FindInDocument(doc, "application", "label");
            if(info.label.StartsWith("@")) VER_ICN[LABEL_ID] = info.label;
            else if(int.TryParse(info.label, out labelID)) VER_ICN[LABEL_ID] = String.Format("@{
   
   0}", labelID.ToString("X4"));
            // Fill up the support screen field  不需要返回,注释
            //extractSupportScreens(info, doc);
            if(info.versionCode == null) info.versionCode = fuzzFindInDocument(doc, "manifest", "versionCode");
            if(info.versionName == null) info.versionName = fuzzFindInDocument(doc, "manifest", "versionName");
            else if(info.versionName.StartsWith("@")) VER_ICN[VER_ID] = info.versionName;
            String id = FindInDocument(doc, "application", "android:icon");
            if(null == id)
            {
   
   
                id = fuzzFindInDocument(doc, "manifest", "icon");
            }
            if(null == id)
            {
   
   
                Debug.WriteLine("icon resId Not Found!");
                return info;
            }#
            region 获取APK名称的代码暂时注释, 运行时间太卡顿
            // Find real strings
            if(!info.hasIcon && id != null)
            {
   
   
                if(id.StartsWith("@android:")) VER_ICN[ICN_ID] = "@" + (id.Substring("@android:".Length));
                else VER_ICN[ICN_ID] = String.Format("@{0}", Convert.ToInt32(id).ToString("X4"));
                List < String > resId = new List < String > ();
                for(int i = 0; i < VER_ICN.Length; i++)
                {
   
   
                    if(VER_ICN[i].StartsWith("@")) resId.Add(VER_ICN[i]);
                }
                ApkResourceFinder finder = new ApkResourceFinder();
                info.resStrings = finder.processResourceTable(info.resourcesFileBytes, resId);
                if(!VER_ICN[VER_ID].Equals(""))
                {
                    List < String > versions = null;
                    if(info.resStrings.ContainsKey(VER_ICN[VER_ID].ToUpper())) versions = info.resStrings[VER_ICN[VER_ID].ToUpper()];
                    if(versions != null)
                    {
                        if(versions.Count > 0) info.versionName = versions[0];
                    }
                    else
                    {
                        throw new Exception("VersionName Cant Find in resource with id " + VER_ICN[VER_ID]);
                    }
                }
                List < String > iconPaths = null;
                if(info.resStrings.ContainsKey(VER_ICN[ICN_ID].ToUpper())) iconPaths = info.resStrings[VER_ICN[ICN_ID].ToUpper()];
                if(iconPaths != null && iconPaths.Count > 0)
                {
   
   
                    info.iconFileNameToGet = new List < String > ();
                    info.iconFileName = new List < string > ();
                    foreach(String iconFileName in iconPaths)
                    {
   
   
                        if(iconFileName != null)
                        {
   
   
                            if(iconFileName.Contains(@"/"))
                            {
   
   
                                info.iconFileNameToGet.Add(iconFileName);
                                info.iconFileName.Add(iconFileName);
                                info.hasIcon = true;
                            }
                        }
                    }
                }
                else
                {
   
   
                    throw new Exception("Icon Cant Find in resource with id " + VER_ICN[ICN_ID]);
                }
                if(!VER_ICN[LABEL_ID].Equals(""))
                {
   
   
                    List < String > labels = null;
                    if(info.resStrings.ContainsKey(VER_ICN[LABEL_ID])) labels = info.resStrings[VER_ICN[LABEL_ID]];
                    if(labels.Count > 0)
                    {
   
   
                        info.label = labels[0];
                    }
                }
            }#
            endregion
        }
        catch(Exception e)
        {
   
   
            throw e;
        }
        return info;
    }
    private void ExtractPermission(ApkInfo info, XmlDocument doc, String keyName, String attribName)
    {
   
   
        XmlNodeList usesPermissions = doc.GetElementsByTagName(keyName);
        if(usesPermissions != null)
        {
   
   
            for(int s = 0; s < usesPermissions.Count; s++)
            {
   
   
                XmlNode permissionNode = usesPermissions.Item(s);
                if(permissionNode.NodeType == XmlNodeType.Element)
                {
   
   
                    XmlNode node = permissionNode.Attributes.GetNamedItem(attribName);
                    if(node != null) info.Permissions.Add(node.Value);
                }
            }
        }
    }
    private String FindInDocument(XmlDocument doc, String keyName, String attribName)
    {
   
   
        XmlNodeList usesPermissions = doc.GetElementsByTagName(keyName);
        if(usesPermissions != null)
        {
   
   
            for(int s = 0; s < usesPermissions.Count; s++)
            {
   
   
                XmlNode permissionNode = usesPermissions.Item(s);
                if(permissionNode.NodeType == XmlNodeType.Element)
                {
   
   
                    XmlNode node = permissionNode.Attributes.GetNamedItem(attribName);
                    if(node != null) return node.Value;
                }
            }
        }
        return null;
    }
}

4、APK解析返回类

public class ApkInfo
{
   
   
    /// <summary>
    /// APK名称
    /// </summary>
    public string label
    {
   
   
        get;
        set;
    }
    /// <summary>
    /// APK版本号
    /// </summary>
    public string versionName
    {
   
   
        get;
        set;
    }
    /// <summary>
    /// APK版本编号
    /// </summary>
    public string versionCode
    {
   
   
        get;
        set;
    }
    /// <summary>
    /// APK支持的最小SDK版本
    /// </summary>
    public string minSdkVersion
    {
   
   
        get;
        set;
    }
    /// <summary>
    /// APK的目标SDK版本
    /// </summary>
    public string targetSdkVersion
    {
   
   
        get;
        set;
    }
    /// <summary>
    /// APK包名称
    /// </summary>
    public string packageName
    {
   
   
        get;
        set;
    }
    public static int FINE = 0;
    public static int NULL_VERSION_CODE = 1;
    public static int NULL_VERSION_NAME = 2;
    public static int NULL_PERMISSION = 3;
    public static int NULL_ICON = 4;
    public static int NULL_CERT_FILE = 5;
    public static int BAD_CERT = 6;
    public static int NULL_SF_FILE = 7;
    public static int BAD_SF = 8;
    public static int NULL_MANIFEST = 9;
    public static int NULL_RESOURCES = 10;
    public static int NULL_DEX = 13;
    public static int NULL_METAINFO = 14;
    public static int BAD_JAR = 11;
    public static int BAD_READ_INFO = 12;
    public static int NULL_FILE = 15;
    public static int HAS_REF = 16;
    // 其他不返回属性权限、其他资源文件等等
    public List < String > Permissions;
    public List < String > iconFileName;
    public List < String > iconFileNameToGet;
    public List < String > iconHash;
    public String resourcesFileName;
    public byte[] resourcesFileBytes;
    public bool hasIcon;
    public bool supportSmallScreens;
    public bool supportNormalScreens;
    public bool supportLargeScreens;
    public bool supportAnyDensity;
    public Dictionary < String, List < String >> resStrings;
    public Dictionary < String, String > layoutStrings;
    public static bool supportSmallScreen(byte[] dpi)
    {
   
   
        if(dpi[0] == 1) return true;
        return false;
    }
    public static bool supportNormalScreen(byte[] dpi)
    {
   
   
        if(dpi[1] == 1) return true;
        return false;
    }
    public static bool supportLargeScreen(byte[] dpi)
        {
   
   
            if(dpi[2] == 1) return true;
            return false;
        }
        //public byte[] getDPI()
        //{
   
   
        //    byte[] dpi = new byte[3];
        //    if (this.supportAnyDensity)
        //    {
   
   
        //        dpi[0] = 1;
        //        dpi[1] = 1;
        //        dpi[2] = 1;
        //    }
        //    else
        //    {
   
   
        //        if (this.supportSmallScreens)
        //            dpi[0] = 1;
        //        if (this.supportNormalScreens)
        //            dpi[1] = 1;
        //        if (this.supportLargeScreens)
        //            dpi[2] = 1;
        //    }
        //    return dpi;
        //}
    public ApkInfo()
    {
   
   
        hasIcon = false;
        supportSmallScreens = false;
        supportNormalScreens = false;
        supportLargeScreens = false;
        supportAnyDensity = true;
        versionCode = null;
        versionName = null;
        iconFileName = null;
        iconFileNameToGet = null;
        Permissions = new List < String > ();
    }
    private bool isReference(List < String > strs)
    {
   
   
        try
        {
   
   
            foreach(String str in strs)
            {
   
   
                if(isReference(str)) return true;
            }
        }
        catch(Exception e)
        {
   
   
            throw e;
        }
        return false;
    }
    private bool isReference(String str)
    {
   
   
        try
        {
   
   
            if(str != null && str.StartsWith("@"))
            {
   
   
                int.Parse(str, System.Globalization.NumberStyles.HexNumber);
                return true;
            }
        }
        catch(Exception e)
        {
   
   
            throw e;
        }
        return false;
    }
}

以上就是.net core 从(本地)服务器获取APK文件并解析APK信息的介绍,做此记录,如有帮助,欢迎点赞关注收藏!

目录
相关文章
|
5天前
|
域名解析 监控 负载均衡
【域名解析DNS专栏】智能DNS解析:自动选择最快服务器的奥秘
【5月更文挑战第27天】智能DNS解析是动态根据用户网络环境和服务器负载,选择最佳服务器的技术,提升用户体验。它通过实时监控服务器负载、网络延迟,运用负载均衡算法、地理位置识别和实时测试,自动选择最快服务器。伪代码展示了其基本工作流程,包括获取用户位置、计算服务器权重并选择最佳服务器进行域名解析。智能DNS解析优化了网络服务的稳定性和效率。
|
6天前
|
域名解析 网络协议 Ubuntu
【域名解析DNS专栏】搭建私有DNS服务器:从BIND到CoreDNS的选择
【5月更文挑战第26天】本文对比了两种流行的DNS服务器软件BIND和CoreDNS。BIND以其稳定性及丰富功能著称,广泛兼容各类平台,适合复杂环境;CoreDNS则以其高性能、模块化设计和易用性脱颖而出。根据需求、资源和技术水平,用户可选择适合自己的DNS服务器。安装示例包括BIND在Ubuntu上的apt安装及基本配置,以及CoreDNS的snap安装和YAML配置。
|
8天前
|
存储 弹性计算 人工智能
【阿里云弹性计算】深度解析阿里云ECS弹性裸金属服务器:性能与弹性的完美平衡
【5月更文挑战第24天】阿里云ECS弹性裸金属服务器融合物理机高性能与云服务弹性,提供计算、存储及网络优势。支持秒级伸缩、自动扩展,适用于高性能计算、游戏、企业应用及AI场景。示例代码展示如何通过CLI创建实例,是高需求场景的理想选择。
60 0
|
8天前
|
域名解析 缓存 网络协议
【域名解析DNS专栏】深入理解DNS根服务器与顶级域服务器
【5月更文挑战第24天】DNS的根服务器和顶级域服务器在域名解析中起关键作用。根服务器是核心,负责提供顶级域服务器引用,维护顶级域列表;顶级域服务器管理如.com的域名,处理二级域名解析和管理。这两者影响解析速度、可靠性和安全性。了解它们有助于优化DNS配置和提升网站访问体验。
【域名解析DNS专栏】深入理解DNS根服务器与顶级域服务器
|
10天前
|
弹性计算 数据挖掘 应用服务中间件
阿里云服务器通用算力型U1实例解析,实例性能、适用场景及常见问题参考
在阿里云服务器的所有实例规格中,通用算力型u1实例主打的是高性价比,通用算力型U1实例云服务器自推出以来,就受到了广大用户的关注,也是目前阿里云的活动中比较热门的云服务器实例,这个实例规格的性能要好于经济型e等共享型实例,价格又比计算型c7、通用型g7等其他企业级实例要低一些。本文将深入解析通用算力型U1实例的特点、适用场景以及价格优势,帮助用户更好地了解该云服务器实例。
阿里云服务器通用算力型U1实例解析,实例性能、适用场景及常见问题参考
|
17天前
|
Android开发 开发者
Android Split APK介绍
【2月更文挑战第5天】
|
8月前
|
SQL 人工智能 算法
Android性能优化之应用瘦身(APK瘦身)
Android性能优化之应用瘦身(APK瘦身)
|
8月前
|
数据安全/隐私保护 Android开发
Android bundetool 转换 .aab 为apk 步骤
Android bundetool 转换 .aab 为apk 步骤
312 0
Android bundetool 转换 .aab 为apk 步骤
|
4天前
|
XML 存储 开发工具
Android Studio如何将APK下载
【5月更文挑战第16天】
|
15天前
|
设计模式 缓存 Java
补齐Android技能树——从AGP构建过程到APK打包过程,安卓rxjava面试
补齐Android技能树——从AGP构建过程到APK打包过程,安卓rxjava面试

推荐镜像

更多
http://www.vxiaotou.com