dongtan9518 2011-11-23 22:58
浏览 60
已采纳

使用Xcode发布json

I am trying to send data, in json format to my webservice, using POST. I have a php page on my server that receives the json string and prints it out.

The issue is, that the POST array recieved is empty, below is my code on my application:

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

The check.php has the following code:

<?php

    print_r($_POST);
?>

I am getting the following output: Array( )

I have tried everything, and cannot seem to get the json string sent to my webservice. I am sure, I am missing something, however I do not know what it is.

  • 写回答

1条回答 默认 最新

  • duan19913 2011-11-28 17:32
    关注

    I got it to work, I had to use the ASIHTTP library. below is the code:

    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];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 深度学习残差模块模型
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)