Tuesday, 6 June 2017

afnetworking can't send body to node.js server, how use?

AFNetworking set the http body, but my node.js server can't recv the body.

Use the NSURLConnection can work.

    //第一步,创建URL
NSURL *testurl = [NSURL URLWithString:@"http://192.168.1.7:1111/xx/xx/xxx"];
//第二步,创建请求
NSMutableURLRequest *testrequest = [[NSMutableURLRequest alloc]initWithURL:testurl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
[testrequest setHTTPMethod:@"POST"];//设置请求方式为POST,默认为GET
NSString *str = @"{'body':{'command':'xxxxx'}}";//设置参数
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
[testrequest setHTTPBody:data];
//第三步,连接服务器

NSData *received = [NSURLConnection sendSynchronousRequest:testrequest returningResponse:nil error:nil];

NSString *str1 = [[NSString alloc]initWithData:received encoding:NSUTF8StringEncoding];

NSLog(@"%@",str1);

afnetworking body not work for node.js

NSDictionary *body =  @{ @"body": @{ @"command": @"xxxx"} };
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

AFURLSessionManager *afmanager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:[NSString stringWithFormat:@"http://192.168.1.7:1111/xx/xx/xxx"] 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:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];


[[afmanager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {

    if (!error) {
        NSLog(@"Reply JSON: %@", responseObject);

        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            //blah blah
        }
    } else {
        NSLog(@"Error: %@, %@, %@", error, response, responseObject);
    }
}] resume];

Node.js server, use express.

req.on('data', function (chunk) {
    body.push(chunk);
});

enter image description here

This image is charles captured data. Seems like same, and I can't capture the hex value to compare they are really different!!!!



via kings0527

No comments:

Post a Comment