微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐