在 Xcode 中使用 NSURLConnection 发送 JSON 数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11033448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 00:36:12  来源:igfitidea点击:

Send JSON data with NSURLConnection in Xcode

objective-cxcodejson

提问by Nick

I am trying to send JSON data to a web server via the code below. For some reason, the request does not seem to be going out. What does it look like I am missing? Also the result from NSURLConnection (retStr) is always empty?

我正在尝试通过以下代码将 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];

采纳答案by Nicolas Manzini

To send simple data in post vars to your webserver running php you simply do this in

要将 post vars 中的简单数据发送到运行 php 的网络服务器,您只需在

Example

例子

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

Implement

实施

-(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
}

回答by codeburn

Instead of sending as JSON, you could simply send it the normal way - by setting the request's HTTPBody with POST method.

您可以简单地以正常方式发送,而不是作为 JSON 发送 - 通过使用 POST 方法设置请求的 HTTPBody。

Only differenc you need to make if you need to make a call such as 'http://abc.example.com/user_profile.json?user[first_name]=fdffdf&user[last_name]=dffdf'

如果您需要拨打诸如“http://abc.example.com/user_profile.json?user[first_name]=fdffdf&user[last_name]=dffdf”之类的电话,则只需要进行区分

is, you need to have your dictionary keys have a prefix. That is, 'first_name=fdffdf' needs to be changed to 'user[first_name]=fdffdf'.

是,你需要让你的字典键有一个前缀。即'first_name=fdffdf'需要改为'user[first_name]=fdffdf'。

Try this bit of code to change your parameter dictionary to the required format for JSON..

试试这段代码,将您的参数字典更改为 JSON 所需的格式。

for (id key in [self allKeys]) {
NSString *newKey = [NSString stringWithFormat:@"%@[%@]", parent, key];
[result setObject:[self objectForKey:key] forKey:newKey];
} 

回答by ganesh manoj

once check like this

一旦像这样检查

ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:[NSURL URLWithString:@"ur url"]];

ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:[NSURL URLWithString:@"ur url"]];

[request setPostValue:appdelegate.userid forKey:@"userid"];
[request setPostValue:self.nameLbl.text forKey:@"username"];
[request setPostValue:self.website.text forKey:@"website"];

NSLog(@"~~~~~~ request~~~~~ %@",request);

[request setTimeOutSeconds:5000];
[request startSynchronous];