首页 > 代码库 > iOS application/json上传文件等

iOS application/json上传文件等

在和sever后台交互的过程中、有时候、他们需要我们iOS开发者以“application/json”形式上传。

 

    NSString *accessUrl = [NSString stringWithFormat:@"%@/xxx",@"https://www.xxxxx.com:xxxx"];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:accessUrl]];
    
    request.HTTPMethod = @"POST";
    
    //设置请求头
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    //设置请求体
    NSMutableData *body = [NSMutableData data];
    
    [body appendData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]];
    
    [request setHTTPBody:body];
    
    NSHTTPURLResponse* urlResponse = nil;
    NSError *error = [[NSError alloc] init];
    NSData *responseData = http://www.mamicode.com/[NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
    
    NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    
    if (result == nil) {
        NSLog(@"json解析失败!");
    }
    
    else
    {
        NSData *jsonData =http://www.mamicode.com/ [result dataUsingEncoding:NSUTF8StringEncoding];
        NSError *err;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                            options:NSJSONReadingMutableContainers
                                                              error:&err];
        if(err) {
            NSLog(@"json解析失败:%@",err);
        }
        success(dic);
    }

 

iOS application/json上传文件等