使用NSMutableURLRequest发送json数据

使用苹果自带的类NSMutableURLRequest post发送数据

使用苹果自带的类NSJSONSerialization解析数据

省去使用第三方库带来的烦恼


//传送json数据

- (IBAction)sendJsonData:(id)sender

{

    // NSURL *url = [[NSURL alloc] initWithString:@"http://tianjianweisai.xicp.net:9090/CloserWebService/servlet/LoginServlet"];

    NSURL *url = [[NSURL alloc] initWithString:@"http://192.168.0.210:8080/CloserWebService/servlet/LoginServlet"];

    //创建一个请求,用于发送

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];

    assert(request != nil);

    [request setTimeoutInterval:5.0f];

    NSString *name = @"smile";

   NSString *age = @"17";

   //使用苹果自带的类NSJSONSerialization生成json

    NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:name,@"username",age,@"password",nil];

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];

   //下面的二次转换很重要,因为使用NSJSONSerialization生成的data不能直接传给服务端,服务端必须要根据一个名字来读取数据,下面就是给jsonData格式化并取个名称

    NSString *strData = [[NSString alloc] initWithData:jsonData encoding:NSASCIIStringEncoding];

    NSLog(@"strData:%@",strData);

    NSString *postData = [[NSString alloc] initWithFormat:@"message%@",strData];


    NSData *sendData = [postData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; //这个sendData才可以发送给服务端

    NSString *postLength = [NSString stringWithFormat:@"%d", [sendData length]];


    [request setHTTPMethod:@"POST"];

    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];

    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

    [request setHTTPBody:sendData];

    //使用NSURLConnection的类方法sendSynchronousRequest:request发送数据

    [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

    

    

    NSHTTPURLResponse* urlResponse = nil;

    NSError *error = [[NSError alloc] init];

    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值