c# - iOS http POST 请求

标签 c# ios ipad http

我在服务器上有一个 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/

相关文章:

ios - Adobe RM SDK 注释

ios - 归档 ResearchKit 应用程序 : Getting "ld: symbol(s) not found for architecture arm64"

iphone - 如何以编程方式为特定 UITextField 设置返回键?

ios - 如何修复 UIPopoverController 中呈现的 UIActivityViewController 的内存泄漏

c# - 更新面板内的异步文件上传和触发回发的下拉列表不起作用

c# - 在编辑其值时访问 Datagridview 单元格值

c# - 如何让 excel UDF 返回实际日期时间而不是一般日期时间或 double 日期时间?

c# - GroupBy 无法翻译

ios - UIImageView 纵横比?

ios - 如何测试应用本地化?