使用Xcode发布json

时间:2011-11-23 22:58:46

标签: php json post xcode4 nsmutableurlrequest

我正在尝试使用POST以json格式将数据发送到我的webservice。我的服务器上有一个php页面,它接收json字符串并将其打印出来。

问题是,收到的POST数组是空的,下面是我的应用程序上的代码:

NSString *jsonRequest = @"{\"username\":\"james\",\"password\":\"james1234\"}";
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
NSURL *url = [NSURL URLWithString:[[NSString alloc] initWithFormat:@"http://mydomain.com/check.php"]];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];

[request setHTTPMethod:@"POST"];
[request setHTTPBody:requestData];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d",[requestData length]] forHTTPHeaderField:@"Content-Length"];

[NSURLConnection connectionWithRequest:[request autorelease] delegate:self];

check.php包含以下代码:

<?php

    print_r($_POST);
?>

我得到以下输出:         阵列(               )

我已经尝试了一切,似乎无法将json字符串发送到我的webservice。我确信,我错过了一些东西,但我不知道它是什么。

1 个答案:

答案 0 :(得分:2)

我让它工作,我不得不使用ASIHTTP库。下面是代码:

NSURL *url = [NSURL URLWithString:[[NSString alloc] initWithFormat:@"http://mydomain.com/check.php"]];

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setRequestMethod:@"POST"];
[request setDelegate:self];
[request setPostValue:@"james" forKey:@"username"];
[request setPostValue:@"james1234" forKey:@"password"];
[request startAsynchronous];