• NSMutableURLRequest POST数据实现


       本文转自  http://www.999dh.net/article/iphone_ios_art/29.html  转载请注明,谢谢!

        今天晚上是个值得庆祝的日子啊,我在iphone上对网络编码又懂了一些。
       
        原来在MTK上,通过HTTP协议 把数据POST到服务器,最近想把他弄到iphone上来,经过几天的努力,终于有效果了。大概的代码如下:

        NSString * strURL = @"http://211.xxx.2.123:8080/terminal/gprs";//这里IP地址为了保密
        
        NSString * str = [[NSString alloc]initWithString:@"[2012112618351111,T21,60,16@111111111111111111@222222222222222222@333333333333333333]"];
        NSData * postData = [str dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
        NSString * strLen = [NSString stringWithFormat:@"%d",[postData length]];
        
        NSMutableURLRequest * request = [[[NSMutableURLRequest alloc]init]autorelease];
        [request setURL:[NSURL URLWithString:strURL]];
        [request setHTTPMethod:@"POST"];
        [request setValue:strLen forHTTPHeaderField:@"Content-Length"];
        [request setValue:@"18213997120" forHTTPHeaderField:@"User Agent"];
        [request setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];
        [request setValue:@"zh-cn" forHTTPHeaderField:@"Accept-Language"];
        [request setValue:@"*/*" forHTTPHeaderField:@"Accept"];
        //本来在这里还有一个 设置HOST的代码的,但是这个代码有的话 会返回 400 badrequest错误
        //具体原因暂时不清楚,以后再说
       //[request setValue:strURL forHTTPHeaderField:@"Host"];
        [request setHTTPBody:postData];
            
        NSURLResponse *response = nil;
        
        NSError *error = nil;
        
        NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
        
        NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];  
        NSLog(@"====%@",returnString);  
        
        if( nil == error )
        {
            NSLog(@"nil == error");
        }
        else
        {
            NSLog(@"nil != error");
        }
        
        if( nil == response )
        {
            NSLog(@"nil == response");
        }
        else
        {
            NSLog(@"nil != response");
            
            int statusCode = [(NSHTTPURLResponse*)response statusCode];
            NSLog(@"code:%d",statusCode);
        }


    庆祝下   庆祝下~~~~ 

  • 相关阅读:
    ArrayList源码分析_JDK1.8.0_191
    LinkedList源码分析_JDK1.8.0_191
    HashMap源码分析_JDK1.8.0_191
    生产者消费者模型Java实现
    INT整型最小值取负还是本身的问题
    字节跳动面试题
    go sqlx操作数据库问题
    go gin框架调用cmd运行python脚本问题
    Android视频播放不能使用自研播放器
    mac python版本错误问题以及pip版本错误(anacanda)
  • 原文地址:https://www.cnblogs.com/rollrock/p/2791474.html
Copyright © 2020-2023  润新知