将 JSON 数据放入 NSURL 中
我正在尝试做一些看似理所当然的事情,但由于某种原因不起作用。
我正在尝试发出 JSON 数据的获取请求,并在 URL 中发送 JSON“数据”参数。
这是我正在使用的代码:
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 为空。我不太明白为什么它会被破坏,但我认为发送 { 或 " 会破坏它。有什么想法吗?我应该切换到 POST 吗?
I'm trying to do something that seems like a no brainer, but for some reason isn't working.
I'm trying to make a get request for JSON data, sending a JSON 'data' parameter in the URL.
Here's the code I'm using:
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"}
When I set a breakpoint, theUrl is null. I can't quite figure out why it's breaking, but I figure something about sending the {'s or "'s is breaking it. Any ideas? Should I just switch to POST?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您切换了方法
stringByAddingPercentEscapesUsingEncoding:
通过
stringByReplacingPercentEscapesUsingEncoding
请参阅:
http://developer.apple.com/library /mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html
http://blog.evandavey.com/2009/ 01/如何对 url-encode-nsstring-in-objective-c.html
you switched method
stringByAddingPercentEscapesUsingEncoding:
by
stringByReplacingPercentEscapesUsingEncoding
see:
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
您应该考虑在请求中发送 HTTP 身份验证标头,而不是在 URL 本身中发送用户名和密码。
像这样的东西:
[请求 setValue:[whatToPost 描述] forHTTPHeaderField:@"授权"];
当然,这假设您控制着事务的另一端,即您正在访问的 Web 服务。
You should look into sending an HTTP Authentication header in the request instead of sending the username and password in the URL itself.
Something like:
[request setValue:[whatToPost descripiption] forHTTPHeaderField:@"Authorization"];
Of course, this assumes that you are in control of the other end of the transaction, i.e. the web service that you are hitting.