• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

iphone - 将文本/数据以及特殊字符作为参数添加到 iphone 中的 api(url)

[复制链接]
菜鸟教程小白 发表于 2022-12-12 22:39:26 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我是 Obj-c 的新手。我正在向 url 添加像文本这样的参数(文本也可能有特殊字符)。但是 url 显示为零,它没有从字符串中获取值。

例如:

NSString*strUrl=[NSString stringWithFormat"hi how@!#$%^^&*()_=+   r u <>,./ where r u"];

NSString *strMainUrl=[NSString stringWithFormat"http://google.com/API/index.php action=listIt&data=%@",strUrl];

NSString *encodeStr = [string stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSURL *url=[NSURL URLWithString:encodeStr];

NSLog(@" url is =%@",url);

但 url 显示 nil 值。它没有采用“encodeStr”值。我该如何解决这个问题。请帮助我。

我试过了..

NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:str] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30.0];

还有

strEncode=[strEncode stringByReplacingPercentEscapesUsingEncoding:NSASCIIStringEncoding];



Best Answer-推荐答案


here 中的修改示例:

#import <Foundation/Foundation.h>

// In case you're unfamiliar, this is a category, which allows us to add methods
// to an existing class, even if we didn't create it. It's a nice alternative
// to subclassing.
//
// In this case, we're extending NSString
@interface NSString (URLEncoding)
-(NSString *)urlEncodeUsingEncodingNSStringEncoding)encoding;
@end

@implementation NSString (URLEncoding)
-(NSString *)urlEncodeUsingEncodingNSStringEncoding)encoding {
    return (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
               (CFStringRef)self,
               NULL,
               (CFStringRef)@"!*'\"();&=+$,/?%#[]% ",
               CFStringConvertNSStringEncodingToEncoding(encoding));
}
@end

int main(int argc, char *argv[]) {
    @autoreleasepool 
    {
        NSString *raw = @"hi how@!#$%^^&*()_=+   r u <>,./ where r u";

            // note also, that your string omits the '?' in the URL
        NSString *url = [NSString stringWithFormat"http://google.com/API/index.php?action=listIt&data=%@",
                    [raw urlEncodeUsingEncoding:NSUTF8StringEncoding]];

        NSURL *finalUrl = [NSURL URLWithString:url];

        NSLog(@"%@", finalUrl);
    }
}

输出:

http://google.com/API/index.php?action=listIt&data=hi%20how%40%21%23%24%25%5E%5E%26%2A%28%29_%3D%2B%20%20%20r%20u%20%3C%3E%2C.%2F%20where%20r%20u

关于iphone - 将文本/数据以及特殊字符作为参数添加到 iphone 中的 api(url),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12219547/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap