2013-07-31 82 views
0

我在服务器上有一个API,我试图从中获取JSON响应。我已经使用了几个请求工具来模拟一个调用,并且每次都得到正确的数据。以下是我的请求设置:iOS http POST请求

NSString *post = [NSString stringWithFormat:@"user_id=%@&last_sync=%@",user_id, last_sync]; 
NSURL *directoryURL = [NSURL URLWithString:directoryURI]; 
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:directoryURL]; 

[request setHTTPMethod:@"POST"]; 
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 
[request setHTTPBody:[NSData dataWithBytes:[post UTF8String] length:[post length]]]; 

我的模拟请求中的内容类型也相同。没有错误返回,只是没有内容。

+0

'@ “USER_ID =%@&last_sync =%@”'这不是POST这是查询字符串 – meda

+0

我转换字符串转换为数据并将其传递给HTTPBody,如下所述:http://developer.apple.com/library/ios/#documentation/NetworkingInternetWeb/Conceptual/NetworkingOverview/WorkingWithHTTPAndHTTPSRequests/WorkingWithHTTPAndHTTPS Requests.html –

+0

如果你有一个JSON API,那么你的头应该看起来像这样:[request setValue:@“application/json”forHTTPHeaderField:@“Accept”]; [request setValue:@“application/json”forHTTPHeaderField:@“Content-Type”];' – meda

回答

1

想通了。显然,与模拟器不同,NSMutableRequest不像当你使用POST变量和URL中的查询字符串变量的组合。将变量移动到POST正文中,现在一切正常。

0

如果您使用POST方法,则必须将字符串转换为NSData格式。

希望这会有所帮助。

+0

这是示例代码。我想出了解决办法,但必须等到我可以将其作为答案。谢谢。 –

1

我使用的AFNetworking库,它从HTTP通信中消除了很多痛苦。

我的帖子电话是沿着以下线路:

NSURL *nsURL = [NSURL URLWithString:@"http://someurl.com"]; 
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:nsURL]; 

[request setHTTPMethod:@"POST"]; 
[request addValue:@"xxxx" forHTTPHeaderField:@"yyy"]; // for any header params you want to pass in 
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"]; 

// If you need to pass any JSOn data to your WS 
if (json != nil) [request setHTTPBody:json]; 

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request 
success:^(NSURLRequest *returnedRequest, NSHTTPURLResponse *response, id JSON) 
{ 
    ... 
} 
failure:^(NSURLRequest *returnedRequest, NSHTTPURLResponse *response, NSError *error, id JSON) 
{ 
     ... 
}]; 
0

URL形式参数编码 [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters]; POST http://example.com/ Content-Type: application/x-www-form-urlencoded

foo=bar&baz[]=1&baz[]=2&baz[]=3 JSON Parameter Encoding

[[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters]; POST http://example.com/ Content-Type: application/json {"foo": "bar", "baz": [1,2,3]}