如何在iPhone的Post方法中发送JSON请求? [英] How to sent JSON request in the Post method in iPhone?

查看:107
本文介绍了如何在iPhone的Post方法中发送JSON请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JSON字符串作为对服务器的请求,并以JSON格式获取响应.我已经使用此代码发布数据了,

I am using the JSON string as a request to the server and get the response in the JSON format. I have used this code for posting the data,

NSString *requestString = [NSString stringWithFormat:@"{\"id\":\"1\"}}"];
NSLog(@"the request string is %@", requestString);
NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: @"http//www.aaaa.com"]];
[request setHTTPMethod: @"POST"];
[request setHTTPBody: requestData];
[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
[theConnection start];

if( theConnection ){            
    receiveData = [[NSMutableData data] retain];
}  

在服务器端,他们将核心PHP与post方法一起使用,每当我将请求发送到服务器时,我都无法获取数据,并且JSON请求文件也未到达服务器.所以请帮帮我.

In server side, they have used core PHP with post method, whenever i sent the request to the server, i am not getting the data and JSON request file doesn't reached to the server. So please help me out.

但是上面的代码在另一个项目中运行良好,并且他们在服务器端使用了SOAP.因此,建议我在服务器端或iPhone端在哪里可以更改代码以实现此目的.

But the above code is perfectly working fine in the another project and they have used SOAP in the server side. So please suggest me, where can i change the code to achieve this, in server side or iPhone side.

谢谢!

推荐答案

除了片段"注释,

也请添加以下标题.

[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];

也在这一行

NSString *requestString = [NSString stringWithFormat:@"{\"id\":\"1\"}}"];

它有2个大括号.请检查一下.

it has 2 close braces. Please check it.

更新:

您是否实现了NSURLConnectionDelegate方法?

Have you implemented the NSURLConnectionDelegate methods?

请参考 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆