iOS URL的Encode 与 URLDecode

本文深入探讨了URL编码和解码的过程,提供了详细的Objective-C代码实现,包括如何使用CFURLCreateStringByAddingPercentEscapes和CFURLCreateStringByReplacingPercentEscapes函数进行字符串的编码与解码。
/**
 *  URLEncode
 */
- (NSString *)URLEncodedString:(NSString *)str
{
    // CharactersToBeEscaped = @":/?&=;+!@#$()~',*";
    // CharactersToLeaveUnescaped = @"[].";
    
    NSString *unencodedString = str;
    NSString *encodedString = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (CFStringRef)unencodedString,
                                                              NULL,
                                                              (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                              kCFStringEncodingUTF8));
    
    return encodedString;
}



/**
 *  URLDecode
 */
-(NSString *)URLDecodedString
{
    //NSString *decodedString = [encodedString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding ];
    
    NSString *encodedString = self;
    NSString *decodedString  = (__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL,
                                                                                                                     (__bridge CFStringRef)encodedString,
                                                                                                                     CFSTR(""),
                                                                                                                     CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
    return decodedString;
}


<think>我们正在解决Unity中出现的"invalidurlformat"错误。这个错误通常发生在尝试使用UnityWebRequest或WWW类进行网络请求时,提供的URL格式不正确。可能的原因包括:1.URL字符串包含空格或非法字符。2.URL没有使用正确的协议(如http://或https://)。3.URL字符串在代码中拼接错误(例如,缺少斜杠、包含转义字符等)。4.在iOS平台上,如果没有在Info.plist中配置ATS(AppTransportSecurity)设置,尝试使用http协议(而不是https)也会导致问题。解决方案:1.检查URL字符串,确保其格式正确。可以使用Uri.EscapeUriString或WebUtility.UrlEncodeURL进行编码,避免非法字符。2.确保使用正确的协议。如果使用http,注意iOS平台需要配置ATS(允许http请求)。3.检查拼接的URL是否正确,避免多余或缺失的字符。4.对于iOS平台,如果必须使用http,需要在Info.plist中添加以下内容:<key>NSAppTransportSecurity</key><dict><key>NSAllowsArbitraryLoads</key><true/></dict>示例代码(使用UnityWebRequest):```csharpusingUnityEngine;usingSystem.Collections;usingUnityEngine.Networking;publicclassWebRequestExample:MonoBehaviour{voidStart(){StartCoroutine(GetRequest("http://example.com"));}IEnumeratorGetRequest(stringurl){//检查并处理URL中的非法字符stringescapedUrl=Uri.EscapeUriString(url);using(UnityWebRequestwebRequest=UnityWebRequest.Get(escapedUrl)){yieldreturnwebRequest.SendWebRequest();if(webRequest.result==UnityWebRequest.Result.ConnectionError||webRequest.result==UnityWebRequest.Result.ProtocolError){Debug.LogError("Error:"+webRequest.error);}else{Debug.Log("Received:"+webRequest.downloadHandler.text);}}}}```注意:在Unity2018.1及以上版本,UnityWebRequest的Result枚举有变化,请根据Unity版本调整条件判断。如果问题仍然存在,可以尝试以下步骤:-使用WebUtility.UrlEncodeURL的各个部分进行编码(注意:整个URL不需要编码,但参数部分需要)。-在浏览器中测试相同的URL,确认其有效性。-检查网络权限(例如,Android需要INTERNET权限,iOS需要配置ATS)。引用说明:在Unity中处理URL时,确保格式正确非常重要。特别是在移动平台上,安全设置和网络权限都需要正确配置[^1][^2]。如果上述方法不能解决问题,请检查Unity版本是否存在已知问题。例如,某些Unity版本可能存在网络请求的bug,升级到较新版本可能会解决[^3]。§§相关问题§§1.如何对URL进行编码以避免非法字符?2.在Unity中如何正确处理网络请求的错误?3.UnityWebRequest和WWW类有什么区别?4.在iOS平台上如何配置ATS以允许http请求?</think>### Unity中"Invalid URL Format"错误解决方案 "Invalid URL Format"错误通常发生在使用Unity的**UnityWebRequest**或**WWW**类进行网络请求时,表明提供的URL格式不符合标准要求。以下是系统解决方案: #### 核心原因分析 1. **URL格式非法** - 缺少协议前缀(如`http://`或`https://`) - 包含空格、中文或特殊字符(如`|`、`{`) - 端口号格式错误(如`http://example.com:abc`) 2. **平台差异问题** - iOS平台强制ATS安全策略(仅允许HTTPS) - Android 9+要求加密连接(Cleartext Traffic限制) 3. **代码处理缺陷** - 字符串拼接错误(如漏掉`/`分隔符) - 未对动态参数进行URL编码 #### 解决方案步骤 **1. 基础URL修正** ```csharp // 错误示例:缺少协议头 string badUrl = "www.example.com/api"; // 正确修正: string validUrl = "https://www.example.com/api"; ``` > 所有URL必须以`http://`或`https://`开头 **2. 特殊字符处理** 使用`Uri.EscapeUriString`进行编码: ```csharp string rawUrl = "https://example.com/数据查询?name=张三"; string encodedUrl = Uri.EscapeUriString(rawUrl); // 输出:https://example.com/%E6%95%B0%E6%8D%AE%E6%9F%A5%E8%AF%A2?name=%E5%BC%A0%E4%B8%89 ``` **3. 平台适配方案** **iOS平台**:在`Info.plist`中添加ATS例外 ```xml <key>NSAppTransportSecurity</key> <dict> <key>NSAllowsArbitraryLoads</key> <true/> </dict> ``` **Android平台**:在`AndroidManifest.xml`中启用明文传输 ```xml <application android:usesCleartextTraffic="true"> </application> ``` **4. 请求代码最佳实践** ```csharp IEnumerator LoadData() { // 使用UnityWebRequest替代过时的WWW类 using (UnityWebRequest request = UnityWebRequest.Get("https://example.com/data.json")) { yield return request.SendWebRequest(); if (request.result == UnityWebRequest.Result.ConnectionError) { Debug.LogError($"URL格式错误: {request.error}"); } else { // 处理成功响应 } } } ``` #### 验证工具 1. 在浏览器中直接测试URL有效性 2. 使用Unity的**Debug.Log**输出完整URL检查 3. 第三方验证工具:https://www.url-encode-decode.com/ > **关键提示**:Unity 2018+版本推荐使用`UnityWebRequest`替代`WWW`类,后者在高版本中可能引发兼容性问题[^1][^3]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值