objective-c - 如何发送 POST 和 GET 请求?

标签 objective-c swift post get nsurlsession

我想将我的 JSON 发送到 URL(POSTGET)。

NSMutableDictionary *JSONDict = [[NSMutableDictionary alloc] init];
[JSONDict setValue:"myValue" forKey:"myKey"];

NSData *JSONData = [NSJSONSerialization dataWithJSONObject:self options:kNilOptions error:nil];

我当前的请求代码不起作用。

NSMutableURLRequest *requestData = [[NSMutableURLRequest alloc] init];

[requestData setURL:[NSURL URLWithString:@"http://fake.url/"];];

[requestData setHTTPMethod:@"POST"];
[requestData setValue:postLength forHTTPHeaderField:@"Content-Length"];
[requestData setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[requestData setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[requestData setHTTPBody:postData];

使用 ASIHTTPRequest不是可靠的答案。

最佳答案

在 iOS 中发送 POSTGET 请求非常简单;并且不需要额外的框架。


POST 请求:

我们首先将 POSTbody(我们想发送的内容)创建为 NSString,然后转换它到 NSData.

NSString *post = [NSString stringWithFormat:@"test=Message&this=isNotReal"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

接下来,我们读取 postDatalength,以便在请求中传递它。

NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

现在我们有了想要发布的内容,我们可以创建一个 NSMutableURLRequest,并包含我们的 postData

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"http://YourURL.com/FakeURL"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:postData];

let post = "test=Message&this=isNotReal"
let postData = post.data(using: String.Encoding.ascii, allowLossyConversion: true)

let postLength = String(postData!.count)

var request = URLRequest(url: URL(string: "http://YourURL.com/FakeURL/PARAMETERS")!)
request.httpMethod = "POST"
request.addValue(postLength, forHTTPHeaderField: "Content-Length")
request.httpBody = postData;

最后,我们可以发送我们的请求,并通过创建一个新的 NSURLSession 来读取回复:

NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
    NSLog(@"Request reply: %@", requestReply);
}] resume];

let session = URLSession(configuration: .default)
session.dataTask(with: request) {data, response, error in
    let requestReply = NSString(data: data!, encoding: String.Encoding.ascii.rawValue)
    print("Request reply: \(requestReply!)")
}.resume()

GET 请求:

GET 请求基本上是一样的,只是没有 HTTPBodyContent-Length

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"http://YourURL.com/FakeURL/PARAMETERS"]];
[request setHTTPMethod:@"GET"];

NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
    NSLog(@"Request reply: %@", requestReply);
}] resume];

var request = URLRequest(url: URL(string: "http://YourURL.com/FakeURL/PARAMETERS")!)
request.httpMethod = "GET"

let session = URLSession(configuration: .default)
session.dataTask(with: request) {data, response, error in
    let requestReply = NSString(data: data!, encoding: String.Encoding.ascii.rawValue)
    print("Request reply: \(requestReply!)")
}.resume()

附带说明,您可以通过将以下内容添加到我们的 NSMutableURLRequest 来添加 Content-Type(和其他数据)。这可能是服务器在请求时需要的,例如 .

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

也可以使用 [(NSHTTPURLResponse*)response statusCode] 读取响应代码。

request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

更新: sendSynchronousRequest 中被弃用 (10.11) 出。

NSURLResponse *requestResponse; NSData *requestHandler = [NSURLConnection sendSynchronousRequest:request returningResponse:&requestResponse error:nil]; NSString *requestReply = [[NSString alloc] initWithBytes:[requestHandler bytes] length:[requestHandler length] encoding:NSASCIIStringEncoding]; NSLog(@"requestReply: %@", requestReply);

关于objective-c - 如何发送 POST 和 GET 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7673127/

相关文章:

objective-c - 如何实现像 Finder 中那样的搜索字段

swift - 我试图在 Swift 3 中以设定的时间间隔获取位置更新,但它每个时间间隔都会运行我的函数很多次,它应该只运行一次

iphone - 使用特定的 image.png 或 image.jpg 调整 SKSpriteNode 和 SKPhysicsBody

reactjs - 如何在 useEffect 中使用新鲜状态,但仅在卸载时执行清理

iphone - 移动到分组 TableView 中不同单元格中的下一个 UITextField

objective-c - 在 Xcode 中自定义日期选择器

javascript - 将js数组传递给php并解析它

php - 如何使用 multipart/form-data 编码发布数组?

objective-c - @selector - 有多个参数?

objective-c - 使用 GCD 创建高优先级串行调度队列