如何使用 NSURLRequest 在 Http 请求中发送 json 数据 [英] How to send json data in the Http request using NSURLRequest
问题描述
我是 Objective-c 的新手,最近我开始在请求/响应上投入大量精力.我有一个可以调用 url(通过 http GET)并解析返回的 json 的工作示例.
I'm new to objective-c and I'm starting to put a great deal of effort into request/response as of recent. I have a working example that can call a url (via http GET) and parse the json returned.
工作示例如下
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog([NSString stringWithFormat:@"Connection failed: %@", [error description]]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
//do something with the json that comes back ... (the fun part)
}
- (void)viewDidLoad
{
[self searchForStuff:@"iPhone"];
}
-(void)searchForStuff:(NSString *)text
{
responseData = [[NSMutableData data] retain];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.whatever.com/json"]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
我的第一个问题是 - 这种方法会扩大规模吗?或者这不是异步的(意味着我在应用程序等待响应时阻塞了 UI 线程)
My first question is - will this approach scale up? Or is this not async (meaning I block the UI thread while the app is waiting for the response)
我的第二个问题是 - 我如何修改请求部分以执行 POST 而不是 GET?就这么简单的修改HttpMethod吗?
My second question is - how might I modify the request part of this to do a POST instead of GET? Is it simply to modify the HttpMethod like so?
[request setHTTPMethod:@"POST"];
最后 - 我如何将一组 json 数据作为一个简单的字符串添加到这篇文章中(例如)
And finally - how do I add a set of json data to this post as a simple string (for example)
{
"magic":{
"real":true
},
"options":{
"happy":true,
"joy":true,
"joy2":true
},
"key":"123"
}
提前致谢
推荐答案
这是我所做的(请注意,进入我的服务器的 JSON 需要是一个具有一个值(另一个字典)的字典,用于 key = question..ie{:question => { 字典} } ):
Here's what I do (please note that the JSON going to my server needs to be a dictionary with one value (another dictionary) for key = question..i.e. {:question => { dictionary } } ):
NSArray *objects = [NSArray arrayWithObjects:[[NSUserDefaults standardUserDefaults]valueForKey:@"StoreNickName"],
[[UIDevice currentDevice] uniqueIdentifier], [dict objectForKey:@"user_question"], nil];
NSArray *keys = [NSArray arrayWithObjects:@"nick_name", @"UDID", @"user_question", nil];
NSDictionary *questionDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSDictionary *jsonDict = [NSDictionary dictionaryWithObject:questionDict forKey:@"question"];
NSString *jsonRequest = [jsonDict JSONRepresentation];
NSLog(@"jsonRequest is %@", jsonRequest);
NSURL *url = [NSURL URLWithString:@"https://xxxxxxx.com/questions"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: requestData];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
receivedData = [[NSMutableData data] retain];
}
然后通过以下方式处理收到的数据:
The receivedData is then handled by:
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [jsonString JSONValue];
NSDictionary *question = [jsonDict objectForKey:@"question"];
这不是 100% 清楚,需要重新阅读,但一切都应该在这里帮助您入门.据我所知,这是异步的.进行这些调用时,我的 UI 没有被锁定.希望有所帮助.
This isn't 100% clear and will take some re-reading, but everything should be here to get you started. And from what I can tell, this is asynchronous. My UI is not locked up while these calls are made. Hope that helps.
这篇关于如何使用 NSURLRequest 在 Http 请求中发送 json 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!