objective-c – 在Xcode中使用NSURLConnection发送JSON数据

前端之家收集整理的这篇文章主要介绍了objective-c – 在Xcode中使用NSURLConnection发送JSON数据前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图通过下面的代码JSON数据发送到Web服务器.由于某种原因,请求似乎没有出去.我错过了什么? NSURLConnection(retStr)的结果也总是空的?

NSDictionary *data = [NSDictionary dictionaryWithObject:@"test sending ios" forKey:@"value1"];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data options:kNilOptions error:&error];

    NSURL *url = [NSURL URLWithString:@"http://webserveraddress"];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url cachePolicy:nil timeoutInterval:60];
[req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[req setValue:[NSString stringWithFormat:@"%d",[jsonData length]] forHTTPHeaderField:@"Content-Length"];
[req setHTTPMethod:@"POST"];
[req setHTTPBody:jsonData];
NSString *retStr = [[NSString alloc] initWithData:[NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil] encoding:NSUTF8StringEncoding];

解决方法

要将post vars中的简单数据发送到运行PHP的web服务器,您只需执行此操作即可

NSString * key = [NSString stringWithFormat:@"var1=%@&var2=%@&var3=%@",@"var1String",@"var2string",[NSnumber numberWithBool:YES]];

NSURL * url = [NSURL URLWithString:@"http://webserver.com/yourScriptPHP.PHP"];

NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];

[request setHTTPMethod:@"POST"];
[request setHTTPBody:[key dataUsingEncoding:NSUTF8StringEncoding]];

[[NSURLConnection alloc] initWithRequest:request delegate:self];
// this is for you to be able to get your server answer. 
// you will need to make your class a delegate of NSURLConnectionDelegate and NSURLConnectionDataDelegate
myClassPointerData = [[NSMutableData data] retain];

实行

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [myClassPointerData appendData:data]
}

-(void)connection:(NSURLConnection *)connection DidFinishLoading {
    // do what you want with myClassPointerData the data that your server did send you back here
    // for info on your server PHP script you just need to do: echo json_encode(array('var1'=> $var1,'var2'=>$var2...));
    // to get your server sending an answer
}

猜你在找的Xcode相关文章