在 iOS 中发送POST 和GET 请求非常简单;并且不需要额外的框架。
POST请求:
我们首先创建POST 的body(因此,我们想发送的内容)为NSString,并将其转换为NSData。
objective-c
NSString *post = [NSString stringWithFormat:@"test=Message&this=isNotReal"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
接下来,我们读取postData 的length,因此我们可以在请求中传递它。
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];
swift
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 来阅读回复:
objective-c
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];
swift
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 请求基本相同,只是没有HTTPBody 和Content-Length。
objective-c
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];
swift
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(和其他数据)。这可能是服务器在请求时需要的,例如 json。
objective-c
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
也可以使用[(NSHTTPURLResponse*)response statusCode]读取响应代码。
swift
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
更新:sendSynchronousRequest 从ios9 和osx-elcapitan (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);