【问题标题】:Put JSON data in NSURL将 JSON 数据放入 NSURL
【发布时间】:2011-11-18 06:35:16
【问题描述】:

我正在尝试做一些看起来很简单的事情,但由于某种原因不起作用。

我正在尝试对 JSON 数据发出 get 请求,在 URL 中发送 JSON 'data' 参数。

这是我正在使用的代码:

NSDictionary *whatToPost= [NSDictionary dictionaryWithObjectsAndKeys:
 username, @"username", 
 password, @"password", nil];

NSString *url = [NSString stringWithFormat:@"http://domain.com/user/get?data=%@",
 [whatToPost JSONString]];
NSURL *theUrl = [NSURL URLWithString:
 [url stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
//NSLog(url) will produce this:
  http://domain.com/user/get?data={"username":"test1","password":"poop"}

当我设置断点时,theUrl 为空。我不太明白它为什么会中断,但我想发送 {'s 或 "'s 会破坏它。有什么想法吗?我应该切换到 POST 吗?

【问题讨论】:

    标签: iphone objective-c json nsurl


    【解决方案1】:
    NSDictionary *whatToPost= [NSDictionary dictionaryWithObjectsAndKeys:
     username, @"username", 
     password, @"password", nil];
    
    NSString *url = [NSString stringWithFormat:@"http://domain.com/user/get?data=%@",
     [whatToPost JSONString]];
    NSURL *theUrl = [NSURL URLWithString:
     [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    

    你切换了方法

    stringByAddingPercentEscapesUsingEncoding:

    使用给定的编码返回接收者的表示,以确定将接收者转换为合法 URL 字符串所需的百分比转义。

    stringByReplacingPercentEscapesUsingEncoding

    返回一个新字符串,通过在接收器中将所有百分比转义替换为由给定编码确定的匹配字符。

    见:
    http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html
    http://blog.evandavey.com/2009/01/how-to-url-encode-nsstring-in-objective-c.html

    【讨论】:

    • 你解决了我的生活!我试图理解出了什么问题!!!空网址。还剩两个小时,我找到了这篇文章,谢谢!!!!!!!!!!!!
    【解决方案2】:

    您应该考虑在请求中发送 HTTP 身份验证标头,而不是在 URL 本身中发送用户名和密码。

    类似: [请求 setValue:[whatToPost 描述] forHTTPHeaderField:@"Authorization"];

    当然,这假设您控制事务的另一端,即您正在访问的 Web 服务。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多