0

我正在尝试请求以下 URL,但收到一条错误消息,提示“数据参数为 nil”。我发现“seller_name”有空间,“amount”有点(。)。我认为这是由 URL 引起的问题。那么有没有办法在不丢失信息的情况下发送具有空格和点的 URL?

NSURL *url1 = [[NSURL alloc]initWithString:[NSString stringWithFormat:@"192.168.1.85/localex_postsale.html?contactid=%@&exchangeid=%@&token=%@&buyerid=%@&seller_name=%@&desc=%@&amount=%@&sellerid=%@",contactid,exchangeid,token,buyervalue,sellers,_Description,_Amount,contactid]];
NSError *errors1;
NSData *data1 = [NSData dataWithContentsOfURL:url1];
NSDictionary *json1 = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:data1 options:kNilOptions error:&errors1];
4

2 回答 2

7

看看中的-stringByAddingPercentEscapesUsingEncoding:方法NSString例如

NSString *myUnencodedString = [NSString stringWithFormat:@"192.168.1.85/localex_postsale.html?contactid=%@&exchangeid=%@&token=%@&buyerid=%@&seller_name=%@&desc=%@&amount=%@&sellerid=%@",contactid,exchangeid,token,buyervalue,sellers,_Description,_Amount,contactid]
NSString *encodedString = [myUnencodedString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *myURL = [[NSURL alloc] initWithString:encodedString]
...

参见:Apple文档

于 2013-11-13T09:40:26.640 回答
0

发生这种情况是因为URL 不应包含空格%20如果有任何空间,它应该被编码。NSString我们可以使用NSUTF8StringEncoding如下方式对空格和特殊字符进行编码

NSString *string = [[NSString stringWithFormat:@"192.168.1.85/localex_postsale.html?contactid=%@&exchangeid=%@&token=%@&buyerid=%@&seller_name=%@&desc=%@&amount=%@&sellerid=%@",contactid,exchangeid,token,buyervalue,sellers,_Description,_Amount,contactid]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url1 = [[NSURL alloc]initWithString:string];
NSError *errors1;
NSData *data1 = [NSData dataWithContentsOfURL:url1];
NSDictionary *json1 = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:data1 options:kNilOptions error:&errors1]; 
于 2013-11-13T09:51:23.930 回答