我在服务器上有一个 API,我试图从中获取 JSON 响应。我用过几个请求工具模拟一次调用,每次都能得到正确的数据。这是我的请求设置:
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]]];
内容类型在我的模拟请求中也是相同的。没有返回错误,只是没有内容。
最佳答案
我使用 AFNetworking 库,它减轻了 HTTP 通信的很多痛苦。
我的 POST 调用如下:
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)
{
...
}];
关于c# - iOS http POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17978060/