我正在尝试请求以下网址,并且收到错误消息“数据参数为零”。我发现'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];
答案 0 :(得分: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]
...
Cf。:Apple documentation。
答案 1 :(得分:0)
这是因为网址不应包含空格。如果有空格,它应该编码为%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];