在 Objective-C 中进行网络请求主要使用 NSURLSession
或 NSURLConnection
(已废弃),其中 POST 和 GET 是两种最常用的 HTTP 请求方法:
| 特性 | GET | POST | |------|-----|------| | 数据位置 | URL 查询字符串 | 请求体 | | 安全性 | 较低(URL 可见) | 较高 | | 数据量限制 | 较小(URL 长度限制) | 较大 | | 缓存 | 可缓存 | 通常不缓存 | | 后退/刷新 | 无害 | 数据会重新提交 | | 书签 | 可收藏为书签 | 不可收藏 |
// 创建URL对象
NSURL *url = [NSURL URLWithString:@"https://example.com/api?param1=value1¶m2=value2"];
// 创建请求对象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 创建会话
NSURLSession *session = [NSURLSession sharedSession];
// 创建任务
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error) {
NSLog(@"Error: %@", error.localizedDescription);
return;
}
if (data) {
NSError *jsonError;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
if (jsonError) {
NSLog(@"JSON Error: %@", jsonError.localizedDescription);
} else {
NSLog(@"Response: %@", json);
}
}
}];
// 启动任务
[task resume];
// 创建URL对象
NSURL *url = [NSURL URLWithString:@"https://example.com/api"];
// 创建请求对象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
// 设置请求头
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
// 准备请求体数据
NSDictionary *postData = @{@"key1": @"value1", @"key2": @"value2"};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postData options:0 error:&error];
if (error) {
NSLog(@"JSON Serialization Error: %@", error.localizedDescription);
return;
}
[request setHTTPBody:jsonData];
// 创建会话
NSURLSession *session = [NSURLSession sharedSession];
// 创建任务
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error) {
NSLog(@"Error: %@", error.localizedDescription);
return;
}
if (data) {
NSError *jsonError;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
if (jsonError) {
NSLog(@"JSON Error: %@", jsonError.localizedDescription);
} else {
NSLog(@"Response: %@", json);
}
}
}];
// 启动任务
[task resume];
原因:网络连接不稳定或服务器响应慢
解决方案:
// 设置请求超时时间
[request setTimeoutInterval:30.0]; // 30秒超时
原因:自签名证书或证书不匹配
解决方案:
// 在 NSURLSession 配置中设置安全策略
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
config.TLSMinimumSupportedProtocol = kTLSProtocol12;
// 或者在 NSURLSessionDelegate 中实现证书验证方法
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler {
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
}
}
原因:URL 编码不正确
解决方案:
NSString *encodedParam = [param stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
原因:网络回调在后台线程执行
解决方案:
dispatch_async(dispatch_get_main_queue(), ^{
// 更新UI代码
});
NSURL *url = [NSURL URLWithString:@"https://example.com/upload"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
// 设置边界字符串
NSString *boundary = @"Boundary-7MA4YWxkTLLu0UIW";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request setValue:contentType forHTTPHeaderField:@"Content-Type"];
// 构建请求体
NSMutableData *body = [NSMutableData data];
// 添加文件数据
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Disposition: form-data; name=\"file\"; filename=\"image.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:UIImageJPEGRepresentation([UIImage imageNamed:@"image.jpg"], 0.8)];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// 添加其他参数
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Disposition: form-data; name=\"param1\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"value1\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// 结束标记
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
// 创建并执行任务...
对于更复杂的网络请求,推荐使用 AFNetworking 等第三方库:
#import <AFNetworking/AFNetworking.h>
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
// GET 请求
[manager GET:@"https://example.com/api"
parameters:@{@"param1": @"value1", @"param2": @"value2"}
progress:nil
success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"Response: %@", responseObject);
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"Error: %@", error.localizedDescription);
}];
// POST 请求
[manager POST:@"https://example.com/api"
parameters:@{@"key1": @"value1", @"key2": @"value2"}
progress:nil
success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"Response: %@", responseObject);
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"Error: %@", error.localizedDescription);
}];
通过以上方法和示例,您可以在 Objective-C 中有效地实现 GET 和 POST 请求,处理各种网络通信需求。
没有搜到相关的文章