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
}

相关文章

在有效期内的苹果开发者账号(类型为个人或者公司账号)。还...
Appuploader官网--IOS ipa上传发布工具,证书制作工具跨平台...
苹果在9月13号凌晨(北京时间)发布 iOS 16,该系统的设备可...
计算机图形学--OpenGL递归实现光线追踪
Xcode 14打出来的包在低版本系统运行时会崩溃,报错信息是Li...