在和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 = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];

    NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];

    if (result == nil) {
        NSLog(@"json解析失败!");
    }

    else
    {
        NSData *jsonData = [result dataUsingEncoding:NSUTF8StringEncoding];
        NSError *err;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                            options:NSJSONReadingMutableContainers
                                                              error:&err];
        if(err) {
            NSLog(@"json解析失败:%@",err);
        }
        success(dic);
    }

 

相关文章

网站地图xml地图