request 请求body丢失

刚接触搞IOS,这个问题也是困扰了好久,今天终于解决了。
关键少了一段断码:[request setValue:@"application/octet-stream" forHTTPHeaderField:@"Content-Type"]; 这个必须设置。


    //拼接URL字符串
    NSString *strUrl = [NSString stringWithFormat:@"http://1xxxxxxxx"];
    
    //1.创建URL资源地址
    NSURL *url = [NSURL URLWithString:strUrl];
    
    //创建Request请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    //2.设置请求方式
    [request setHTTPMethod:@"POST"];
    
    //3.设置超时5秒
    [request setTimeoutInterval:10];
    
    [request setCachePolicy:NSURLRequestUseProtocolCachePolicy];
    
     [request setValue:@"application/octet-stream" forHTTPHeaderField:@"Content-Type"];
    
    
    //将中文转码(url中有中文的时候一定要使用这句)
    
   // param = [param stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    
    
    //4.设置请求报文
    NSData * bodyData = [encodeParam2 dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    [request setHTTPBody:bodyData];


   NSString *aString = [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding];
   NSLog(@"HttpBody Data->Bytes %@", aString);
    

    NSURLSession *session = [NSURLSession sharedSession];
    
    NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //判断是否成功
        if(error)
        {
            NSLog(@"error1=======%@", error.localizedDescription);
        }
        else
        {
            // 如果请求成功,则解析数据。
            id object = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
            // 11、判断是否解析成功
            if (error)
            {
                NSLog(@"error2=======%@", error.localizedDescription);

            }
            else
            {
                // 解析成功,处理数据,通过GCD获取主队列,在主线程中刷新界面。
                NSLog(@"succes ======= %@", object);
            }
        }
    }];
    
    //执行任务
    [task resume];
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值