AFNetworking3.2.1 Post請(qǐng)求通過httpbody傳參

一、使用Jmeter進(jìn)行接口測(cè)試,Headers和請(qǐng)求參數(shù)Parameters 、Body Data 的聯(lián)系

1、使用Parameters時(shí),Content-Type 不傳默認(rèn)值為:application/x-www-from-urlencoded,或者直接傳application/x-www-from-urlencoded,若傳application/json出錯(cuò)。

2、使用Body Data時(shí),Content-Type可傳application/x-www-from-urlencoded或者application/json,兩者的區(qū)別是數(shù)據(jù)格式不同。

二、Headers常用字段

User-Agent、Accept、Content-Type
瀏覽器信息、發(fā)送端希望接收的數(shù)據(jù)類型、發(fā)送端發(fā)送的數(shù)據(jù)類型

三、Content-type

(1)application/x-www-form-urlencoded
POST請(qǐng)求方式,如果不設(shè)置Headers的content-type,基本默認(rèn)會(huì)以 application/x-www-form-urlencoded 方式提交數(shù)據(jù)。

(2)application/json
現(xiàn)在越來越多的人把它作為請(qǐng)求頭,用來告訴服務(wù)端消息主體是序列化后的 JSON 字符串。這種方案,可以方便的提交復(fù)雜的結(jié)構(gòu)化數(shù)據(jù),特別適合 RESTful 的接口。各大抓包工具如 Chrome 自帶的開發(fā)者工具、Firebug、Fiddler,都會(huì)以樹形結(jié)構(gòu)展示 JSON 數(shù)據(jù),非常友好直觀。

(3)multipart/form-data
這種方式一般用來上傳文件。

(4)text/xml
XML 作為編碼方式的遠(yuǎn)程調(diào)用規(guī)范,一般用不到。

四、jmeter 接口應(yīng)用

(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值,因?yàn)樵撝的J(rèn)為application/ x-www-form-urlencoded

image
image

json格式數(shù)據(jù)

image

(4)直接在url后邊拼接參數(shù),get請(qǐng)求方式常用,post請(qǐng)求方式不推薦。


五、AFNetworking3.2.1 post 請(qǐng)求通過httpbody傳參

一般請(qǐng)求的話是這樣

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

但是今天遇到個(gè)不管怎么樣parameters都傳不到服務(wù)器那邊,而后臺(tái)那邊給我的解釋是傳輸用[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.用系統(tǒng)NSURLConnection 請(qǐng)求

      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.用不習(xí)慣系統(tǒng)沒關(guān)系,其實(shí)afn3.0 也有提供api給我們調(diào)用,但是這個(gè)是我一直沒接觸過的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];

參考文獻(xiàn):

jmeter: http采樣器 Parameters、Body Data使用區(qū)別
AFNetworking3.0 How to POST with headers and HTTP Body

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容