首页
学习
活动
专区
圈层
工具
发布

目标C post get请求与正文

Objective-C 中的 POST 与 GET 请求详解

基础概念

在 Objective-C 中进行网络请求主要使用 NSURLSessionNSURLConnection(已废弃),其中 POST 和 GET 是两种最常用的 HTTP 请求方法:

  • GET 请求:从服务器获取数据,参数附加在 URL 后面
  • POST 请求:向服务器发送数据,参数放在请求体中

优势对比

| 特性 | GET | POST | |------|-----|------| | 数据位置 | URL 查询字符串 | 请求体 | | 安全性 | 较低(URL 可见) | 较高 | | 数据量限制 | 较小(URL 长度限制) | 较大 | | 缓存 | 可缓存 | 通常不缓存 | | 后退/刷新 | 无害 | 数据会重新提交 | | 书签 | 可收藏为书签 | 不可收藏 |

实现代码示例

GET 请求示例

代码语言:txt
复制
// 创建URL对象
NSURL *url = [NSURL URLWithString:@"https://example.com/api?param1=value1&param2=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];

POST 请求示例

代码语言:txt
复制
// 创建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];

常见问题及解决方案

1. 请求超时问题

原因:网络连接不稳定或服务器响应慢

解决方案

代码语言:txt
复制
// 设置请求超时时间
[request setTimeoutInterval:30.0]; // 30秒超时

2. HTTPS 证书问题

原因:自签名证书或证书不匹配

解决方案

代码语言:txt
复制
// 在 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);
    }
}

3. 中文参数乱码

原因:URL 编码不正确

解决方案

代码语言:txt
复制
NSString *encodedParam = [param stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

4. 后台线程更新 UI

原因:网络回调在后台线程执行

解决方案

代码语言:txt
复制
dispatch_async(dispatch_get_main_queue(), ^{
    // 更新UI代码
});

应用场景

  1. GET 请求适用场景
    • 获取静态资源(图片、CSS、JS等)
    • 搜索引擎查询
    • 分页数据加载
    • 数据筛选查询
  • POST 请求适用场景
    • 用户登录/注册
    • 表单提交
    • 文件上传
    • 敏感数据传输
    • 大数据量传输

高级用法

文件上传示例

代码语言:txt
复制
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)

对于更复杂的网络请求,推荐使用 AFNetworking 等第三方库:

代码语言:txt
复制
#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 请求,处理各种网络通信需求。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的文章

领券