zoukankan      html  css  js  c++  java
  • Objective-C-使用NSMutableURLRequest发送POST请求,使用NSJSONSerialization解析JSON字符串

    NSString *reqData = @"Data=";
        NSData *postDatas = nil;
        NSString *urlPath = @"url";
        
        //组json字符串数据
        NSMutableDictionary *mulDic = [[[NSMutableDictionary alloc] init] autorelease];
        [mulDic setValue:@"P003" forKey:@"type"];
        
        //NSJSONSerialization 组json字符串
        if ([NSJSONSerialization isValidJSONObject:mulDic]) {
            
            postDatas = [NSJSONSerialization dataWithJSONObject:mulDic options:NSJSONWritingPrettyPrinted error:nil];
            NSString *str = [[NSString alloc] initWithData:postDatas encoding:NSUTF8StringEncoding];
            reqData = [reqData stringByAppendingString:str];
            NSLog(@"reqData:%@",reqData);
            
            //NSData *postData = [reqData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
            postDatas = [NSData dataWithBytes:[reqData UTF8String] length:[reqData length]];
            
        }
        
        NSString *len = [NSString stringWithFormat:@"%d",(int)[postDatas length]];
        NSURL *url = [NSURL URLWithString:urlPath];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        [request setHTTPMethod:@"POST"];
        //[request setValue:@"*/*" forKey:@"accept"];
        //[request setValue:@"Keep-Alive" forKey:@"connection"];
        //[request setValue:@"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)" forKey:@"user-agent"];
        //[request setValue:len forHTTPHeaderField:@"Content-Length"];
        //[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPBody:postDatas];
        
        NSData *retData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        NSString *ret = [[NSString alloc] initWithData:retData encoding:NSUTF8StringEncoding];
        NSLog(@"%@",ret);
        //解析返回的数据JSON格式字符串
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:retData options:NSJSONReadingMutableLeaves error:nil];
        NSLog(@"%@",dic);
  • 相关阅读:
    Asp.net 连接池使用
    关于ASP.NET页面打印技术的总结
    Asp.net页面传值总结
    C#委托
    ASP.NET状态存储管理九大兵器
    JavaScript取ASP.NET中服务器端数据的方法
    DSOFramer.ocx 控件使用
    C#2.0 泛型学习(入门)
    黑马程序员——Java基础String与StringBuilder
    黑马程序员——Java基础语法关键字、常量、变量、运算符
  • 原文地址:https://www.cnblogs.com/fuhaots2009/p/3437000.html
Copyright © 2011-2022 走看看