objective-c – 在Xcode中使用NSURLConnection发送JSON数据
发布时间:2020-12-14 17:30:59 所属栏目:百科 来源:网络整理
导读:我试图通过下面的代码将 JSON数据发送到Web服务器.由于某种原因,请求似乎没有出去.我错过了什么? NSURLConnection(retStr)的结果也总是空的? NSDictionary *data = [NSDictionary dictionaryWithObject:@"test sending ios" forKey:@"value1"];NSError *er
我试图通过下面的代码将
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 } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |