美文网首页
AFNetworking3.2.1 Post请求通过httpbo

AFNetworking3.2.1 Post请求通过httpbo

作者: LINGSHOW | 来源:发表于2019-10-09 09:48 被阅读0次
一、使用Jmeter进行接口测试,Headers和请求参数Parameters 、Body Data 的联系

1、使用Parameters时,Content-Type 不传默认值为:application/x-www-from-urlencoded,或者直接传application/x-www-from-urlencoded,若传application/json出错。

2、使用Body Data时,Content-Type可传application/x-www-from-urlencoded或者application/json,两者的区别是数据格式不同。

二、Headers常用字段

User-Agent、Accept、Content-Type
浏览器信息、发送端希望接收的数据类型、发送端发送的数据类型

三、Content-type

(1)application/x-www-form-urlencoded
POST请求方式,如果不设置Headers的content-type,基本默认会以 application/x-www-form-urlencoded 方式提交数据。

(2)application/json
现在越来越多的人把它作为请求头,用来告诉服务端消息主体是序列化后的 JSON 字符串。这种方案,可以方便的提交复杂的结构化数据,特别适合 RESTful 的接口。各大抓包工具如 Chrome 自带的开发者工具、Firebug、Fiddler,都会以树形结构展示 JSON 数据,非常友好直观。

(3)multipart/form-data
这种方式一般用来上传文件。

(4)text/xml
XML 作为编码方式的远程调用规范,一般用不到。

四、jmeter 接口应用

(1)Content-type=application/x-www-form-urlencoded + Parameters

image

(2)Content-type=application/x-www-form-urlencoded + Body Data

image image

(2)Content-type=application/json + Body Data

添加http信息头管理器,指定Content-Type值,因为该值默认为application/ x-www-form-urlencoded

image image

json格式数据

image

(4)直接在url后边拼接参数,get请求方式常用,post请求方式不推荐。

五、AFNetworking3.2.1 post 请求通过httpbody传参

一般请求的话是这样

AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];
[session POST:@"" parameters:@"" progress:nil success:nil failure:nil];

但是今天遇到个不管怎么样parameters都传不到服务器那边,而后台那边给我的解释是传输用[request setHTTPBody:data];
而 afn 2.0 是这样的

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters
   options:0
     error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

// And finally, add it to HTTP body and job done.
[request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer.timeoutInterval=[[[NSUserDefaults standardUserDefaults] valueForKey:@"timeoutInterval"] longValue];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request progress:nil success:^(NSURLSessionTask *task, id responseObject) {
    NSLog(@"Reply JSON: %@", responseObject);

    }
} failure:^(NSURLSessionTask *operation, NSError *error) {
    NSLog(@"Error: %@, %@, %@, %@, %@", error, operation.responseObject, operation.responseData, operation.responseString, operation.request);

}];
[operation start];

但是3.0弃用了AFHTTPRequestOperationManager,那么怎么才能用呢?
1.用系统NSURLConnection 请求

      NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"url"]];
        [request setHTTPBody:data];
        [request setHTTPMethod:@"POST"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
        NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
    
    
        if (theConnection) {
            NSLog(@"connected");
            receivedData=[[NSMutableData alloc]init];
        } else {
    
            NSLog(@"not connected");
        }
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [receivedData appendData:data];
    NSString* responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"response: %@",responseString);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"Succeeded! Received %lu data",(unsigned long)[receivedData length]);
    NSString* responseString = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
    NSLog(@"response: %@",responseString);
    NSError *myError = nil;
    NSDictionary *res = [NSJSONSerialization JSONObjectWithData:receivedData options:NSJSONReadingMutableLeaves error:&myError];
    NSLog(@"%@",res);
}

2.用不习惯系统没关系,其实afn3.0 也有提供api给我们调用,但是这个是我一直没接触过的AFURLSessionManager。

 AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:@"url" parameters:nil error:nil];
    
    req.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:@"timeoutInterval"] longValue];
    [req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [req setHTTPBody:da];
    
    [[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        
        if (!error) {
            NSLog(@"Reply JSON: %@", responseObject);
        } else {
            NSLog(@"Error: %@, %@, %@", error, response, responseObject);
        }
    }] resume];

参考文献:

jmeter: http采样器 Parameters、Body Data使用区别
AFNetworking3.0 How to POST with headers and HTTP Body

相关文章

网友评论

      本文标题:AFNetworking3.2.1 Post请求通过httpbo

      本文链接:https://www.haomeiwen.com/subject/owewpctx.html