【问题标题】:Send JSON data with NSURLConnection in Xcode在 Xcode 中使用 NSURLConnection 发送 JSON 数据
【发布时间】:2012-06-14 12:53:18
【问题描述】:

我正在尝试通过以下代码将 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 变量发送到您的服务器并从中检索 json。特别是如果您通过 http 连接进行连接会更容易。更容易和更快。你可以简单地把 HTTPBody NSString stringWithFormat:@"var1=%@&var2=%@&var3=%@..." 和你在 php $_POST['var1'], $_POST['var2 '] 等等...
  • @NicolasManzini 你能给我一些示例代码吗?我尝试重新排列上面的代码并删除 NSJSONSerialization,但我的网络服务器上仍然没有收到任何 POST?我需要删除:[[NSString alloc] initWithData:[NSURLConnection sendSynchronousRequest:req returnedResponse:nil error:nil] encoding:NSUTF8StringEncoding]?

标签: objective-c xcode json


【解决方案1】:

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

中执行此操作

示例

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
}

【讨论】:

  • 别忘了释放你的 NSURLCOnnecion 和你的 myClassPointerData
【解决方案2】:

这样检查一次

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

【讨论】:

    【解决方案3】:

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

    只有当您需要拨打电话时,您才需要做不同的事情,例如 'http://abc.example.com/user_profile.json?user[first_name]=fdffdf&user[last_name]=dffdf'

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

    尝试使用这段代码将参数字典更改为 JSON 所需的格式..

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多