如何使用NSURLRequest在Http请求中发送json数据


80

我是Objective-c的新手,从最近开始,我就在请求/响应中投入了大量精力。我有一个工作示例,可以调用url(通过http GET)并解析返回的json。

下面的工作示例

- (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线程)

我的第二个问题是-如何修改请求的一部分以执行POST而不是GET?是否像这样简单地修改HttpMethod?

[request setHTTPMethod:@"POST"];

最后-如何将一组json数据作为简单字符串添加到此帖子中(例如)

{
    "magic":{
               "real":true
            },
    "options":{
               "happy":true,
                "joy":true,
                "joy2":true
              },
    "key":"123"
}

先感谢您


Answers:


105

这是我的工作(请注意,发送到我的服务器的JSON必须是一个字典,其中包含一个用于key = question..ie {: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];
}

然后,receivedData由以下方式处理:

NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [jsonString JSONValue];
NSDictionary *question = [jsonDict objectForKey:@"question"];

这不是100%清楚的,需要重新阅读,但是所有内容都应该在这里,以帮助您入门。据我所知,这是异步的。进行这些调用时,我的UI未被锁定。希望能有所帮助。


除了这一行外,一切看起来都不错[dict objectForKey:@“ user_question”],无];-样本中未声明dict。这只是简单的词典还是特殊的东西?
Toran Billups 2010年

1
对于那个很抱歉。是的,“ dict”只是我从iOS用户文档中加载的简单词典。
Mike G 2010年

19
这是使用NSDictionary实例方法JSONRepresentation。我可能建议我使用NSJSONSerialization类方法dataWithJSONObject,而不是json-framework
罗布

通过像这样的NSNumber将NSUInteger转换为NSString效率更高[[NSNumber numberWithUnsignedInt:requestData.length] stringValue]
尊重TheCode 2013年

1
@MikeG修复了代码示例中长期存在且至今未引起注意的错误。抱歉,编辑您的帖子;)
CouchDeveloper 2013年

7

我为此挣扎了一段时间。在服务器上运行PHP。此代码将发布一个json并从服务器获取json答复

NSURL *url = [NSURL URLWithString:@"http://example.co/index.php"];
NSMutableURLRequest *rq = [NSMutableURLRequest requestWithURL:url];
[rq setHTTPMethod:@"POST"];
NSString *post = [NSString stringWithFormat:@"command1=c1&command2=c2"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding];
[rq setHTTPBody:postData];
[rq setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];

[NSURLConnection sendAsynchronousRequest:rq queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
 {
     if ([data length] > 0 && error == nil){
         NSError *parseError = nil;
         NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
         NSLog(@"Server Response (we want to see a 200 return code) %@",response);
         NSLog(@"dictionary %@",dictionary);
     }
     else if ([data length] == 0 && error == nil){
         NSLog(@"no data returned");
         //no data, but tried
     }
     else if (error != nil)
     {
         NSLog(@"there was a download error");
         //couldn't download

     }
 }];

1
内容类型=“ application / x-www-form-urlencoded”达到目的。谢谢
SamChen 2015年

好答案。我使用的是“ application / json”
Gajendra K Chauhan

6

我建议使用ASIHTTPRequest

ASIHTTPRequest是围绕CFNetwork API的易于使用的包装器,它使与Web服务器通信的一些较繁琐的方面变得更加容易。它用Objective-C编写,可在Mac OS X和iPhone应用程序中使用。

它适合执行基本的HTTP请求并与基于REST的服务(GET / POST / PUT / DELETE)进行交互。包含的ASIFormDataRequest子类使使用multipart / form-data提交POST数据和文件变得容易。


请注意,原始作者已终止该项目。有关原因和替代方法,请参见后续文章:http ://allseeing-i.com/%5Brequest_release%5D ;

我个人是AFNetworking的忠实粉丝


h,我没有。抱歉。
Almo

3

到目前为止,大多数人已经知道了这一点,但是我发布此信息只是为了以防万一,其中有些人仍在iOS6 +中使用JSON挣扎。

在iOS6和更高版本中,我们具有NSJSONSerialization类该类速度很快,并且不依赖于包含“外部”库。

NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[resultStr dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil]; 

这就是iOS6及更高版本现在可以有效地解析JSON的方式.SBJson的使用也是ARC之前的实现,如果您在ARC环境中工作,也会带来这些问题。

我希望这有帮助!


2

这是一篇使用Restkit的精彩文章

它说明了如何将嵌套数据序列化为JSON并将数据附加到HTTP POST请求。


2

由于我对Mike G的答案进行了修改以使代码现代化,因此3到2被拒绝,原因是

此编辑旨在针对帖子的作者,因此没有任何意义。它应该被写为评论或答案

我将编辑内容重新发布为单独的答案。此编辑删除了JSONRepresentation依附关系,NSJSONSerialization正如罗布(Rob)提出的15项意见所建议的那样。

    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"];

    NSLog(@"jsonRequest is %@", jsonRequest);

    NSURL *url = [NSURL URLWithString:@"https://xxxxxxx.com/questions"];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                 cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];


    NSData *requestData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil]; //TODO handle error

    [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];
    }

然后,receivedData由以下方式处理:

NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    NSDictionary *question = [jsonDict objectForKey:@"question"];

0

这是一个使用NSURLConnection + sendAsynchronousRequest:(10.7+,iOS 5+)的更新示例,“ Post”请求与接受的答案相同,为清楚起见在此省略:

NSURL *apiURL = [NSURL URLWithString:
    [NSString stringWithFormat:@"http://www.myserver.com/api/api.php?request=%@", @"someRequest"]];
NSURLRequest *request = [NSURLRequest requestWithURL:apiURL]; // this is using GET, for POST examples see the other answers here on this page
[NSURLConnection sendAsynchronousRequest:request
                                   queue:[NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
     if(data.length) {
         NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
         if(responseString && responseString.length) {
             NSLog(@"%@", responseString);
         }
     }
}];

问题是关于POST
ahmad

2
不,问题的第一部分是关于异步性的,这里没有答案可以回答。为数字投票欢呼。
auco 2014年

0

您可以尝试使用此代码发送json字符串

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:ARRAY_CONTAIN_JSON_STRING options:NSJSONWritin*emphasized text*gPrettyPrinted error:NULL];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *WS_test = [NSString stringWithFormat:@"www.test.com?xyz.php&param=%@",jsonString];
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.