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 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据