Objective C http post 提交 raw 格式的数据

Objective C 2020-04-04 阅读 41 评论 0

使用 Objective C 实现 http post 请求 raw 格式的文本,如 text、json、xml、html 等,只需将待传送的数据,转换成 NSData 对象,再传递给 NSMutableURLRequest 的 setHTTPBody 即可。

实现示例

HttpPostRaw.h

#import <Foundation/Foundation.h>

@interface HttpPostRaw:NSObject
-(id)initWithUrl:(NSString *)urlString;

@property(nonatomic) NSMutableURLRequest *request;
@property(nonatomic) NSString *urlString;
@property(nonatomic) NSMutableDictionary *headers;
@property(nonatomic) NSData *body;

/// 添加请求头
/// @param key 请求头的名
/// @param value 请求头的值
-(void)addHeader:(NSString *)key value:(NSString *)value;

/// 添加参数数据
/// @param body 值
-(void)addFormBody:(NSData *)body;

/// 完成请求
/// @param callback 回调块
- (void)finish:(void(^)(NSData *, NSURLResponse *, NSError *))callback;

@end

HttpPostRaw.m

#import "HttpPostRaw.h"

@implementation HttpPostRaw

-(id)initWithUrl:(NSString *)urlString{
    self.request = [[NSMutableURLRequest alloc]init];
    self.urlString = urlString;
    self.headers = [[NSMutableDictionary alloc]init];
    return self;
}

-(void)addHeader:(NSString *)key value:(NSString *)value{
    [self.headers setObject:value forKey:key];
}

-(void)addFormBody:(NSData *)body{
    self.body = body;
}

- (void)finish:(void (^)(NSData *, NSURLResponse *, NSError *))callback{
    NSURL *url = [[NSURL alloc]initWithString:self.urlString];
    [self.request setURL:url];
    [self.request setHTTPMethod:@"POST"];
    // 添加请求头
    for (NSString *key in self.headers){
        NSString *value = self.headers[key];
        [self.request setValue:value forHTTPHeaderField:key];
    }
    // 添加请求参数
    if (self.body != nil && [self.body length] > 0) {
        [self.request setHTTPBody:self.body];
        // 添加请求头 content-length
        NSString *postLength = [NSString stringWithFormat:@"%ld", [self.body length]];
        [self.request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    }
    
    void (^completionHandler)(NSData *, NSURLResponse *, NSError *) = ^(NSData *data, NSURLResponse *response, NSError *error) {
        if (callback) {
            callback(data, response, error);
        }
    };
    
    [[[NSURLSession sharedSession] dataTaskWithRequest:self.request completionHandler:completionHandler] resume];
}

@end

调用示例

发送 json。

NSString *url = @"http://localhost";
HttpPostRaw *request = [[HttpPostRaw alloc]initWithUrl:url];
// 添加 Content-Type
[request addHeader:@"Content-Type" value:@"application/json"];
NSDictionary *fields = @{@"username": @"test", @"password": @"pwd"};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:fields
                                                   options:NSJSONWritingSortedKeys
                                                     error:&error];
if (!jsonData) {
    NSLog(@"Got an error: %@", error);
} else {
    // 添加 请求参数
    [request addFormBody:jsonData];
}
void (^completionHandler)(NSData *, NSURLResponse *, NSError *) = ^(NSData *data, NSURLResponse *response, NSError *error) {
    if (data == nil || data.length == 0 || response == nil || [(NSHTTPURLResponse *)response statusCode] != 200) {
        NSLog(@"error");
        return;
    }
    NSLog(@"success: %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
};
[request finish:completionHandler];

发送 xml

NSString *url = @"http://localhost";
HttpPostRaw *request = [[HttpPostRaw alloc]initWithUrl:url];
// 添加 Content-Type
[request addHeader:@"Content-Type" value:@"application/xml"];
NSString *fields = @"<xml><username>test</username><password>pwd</password></xml>";
NSData *body = [fields dataUsingEncoding:NSUTF8StringEncoding];
// 添加 请求参数
[request addFormBody:body];
void (^completionHandler)(NSData *, NSURLResponse *, NSError *) = ^(NSData *data, NSURLResponse *response, NSError *error) {
    if (data == nil || data.length == 0 || response == nil || [(NSHTTPURLResponse *)response statusCode] != 200) {
        NSLog(@"error");
        return;
    }
    NSLog(@"success: %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
};
[request finish:completionHandler];
最后更新 2020-04-04
MIP.watch('startSearch', function (newVal, oldVal) { if(newVal) { var keyword = MIP.getData('keyword'); console.log(keyword); // 替换当前历史记录,新增 MIP.viewer.open('/s/' + keyword, {replace: true}); setTimeout(function () { MIP.setData({startSearch: false}) }, 1000); } }); MIP.watch('goHome', function (newVal, oldVal) { MIP.viewer.open('/', {replace: false}); });