IOS总结_IOS以post方式向PHP服务器端发送json数据请求

方法一、使用直接写写入格式

NSURL *url=[NSURLURLWithString:urlString];

    NSMutableURLRequest *requests = [[NSMutableURLRequestalloc]initWithURL:urlcachePolicy:NSURLRequestUseProtocolCachePolicytimeoutInterval:50];

    

    [requests setHTTPMethod:@"POST"];

    

//这是最终的数据格式,只要能够转换成这种格式其他的数据类型均可,但有时候服务器端不能够解析

    NSString *postParams = [NSString stringWithFormat:@"{\"token\":\"IOS_Json_Data\",\"account\":\"%@\",\"password\":\"%@\"}",username,password];


    NSData *data =[postParamsdataUsingEncoding:NSUTF8StringEncoding];

    

    [requests setValue:[NSStringstringWithFormat:@"%lu",(unsignedlong)data.length]forHTTPHeaderField:@"Content-Length"];

    [requests setValue:@"application/json"forHTTPHeaderField:@"Content-Type"];    


    [requests setHTTPBody:data];



方法二、使用AFNetworking框架

 AFHTTPClient *httpClient = [[AFHTTPClientalloc] initWithBaseURL:[NSURLURLWithString:@""]];

    httpClient.parameterEncoding =AFJSONParameterEncoding;

    [httpClient setDefaultHeader:@"Accept"value:@"text/json"];

    

    NSMutableDictionary *params=[[NSMutableDictionaryalloc] init];

    [params setObject:username forKey:@"account"];

    [params setObject:password forKey:@"password"];

    [params setObject:@"token"forKey:@"token"];

    

    

    [httpClient postPath:urlString parameters:params success:^(AFHTTPRequestOperation *operation,id responseObject){

        

        NSLog(@"params ==%@",params);

        NSString *responseStr = [[NSStringalloc] initWithData:responseObjectencoding:NSUTF8StringEncoding];

        

        NSLog(@"Request Successful, response '%@'", responseStr);

    

    }failure:^(AFHTTPRequestOperation *operation,NSError *error)

     {

         NSLog(@"[HTTPClient Error]: %@",error); }];


方法三、使用系统自带的方法

    NSMutableURLRequest *requests = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:50];

    

    [requests setHTTPMethod:@"POST"];

    NSDictionary *jsonDic=[NSDictionarydictionaryWithObjectsAndKeys:@"ios_json_data",@"token",@"testid",@"account",@"testid",@"password",nil];

    NSData *data;

    if ([NSJSONSerializationisValidJSONObject:jsonDic])

    {

        NSError *error;

        data = [NSJSONSerializationdataWithJSONObject:jsonDic options:NSJSONWritingPrettyPrintederror:&error];

    }   

    [requests setValue:[NSStringstringWithFormat:@"%lu",(unsignedlong)data.length]forHTTPHeaderField:@"Content-Length"];

    [requests setValue:@"application/json"forHTTPHeaderField:@"Content-Type"];

    [requests setHTTPBody:data];


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值