返回顶部

收藏

网络编程之POST方法

更多
//Post 提交数据方法:   
- (void)post
{
    NSString *postString = [NSStringstringWithFormat:@"         {\\"userName\\":\\"%@\\",\\"userPass\\":\\"%@\\",\\"version\\":\\"1.0\\"}",self.userField.text,self.passwordField.text]; 
    NSLog(@"%@",postString);
   //一般转化称UTF-8,这里服务器需要ASCII
    NSData* postData = [postStringdataUsingEncoding:NSASCIIStringEncodingallowLossyConversion:YES];
   NSMutableURLRequest *request = [[[NSMutableURLRequestalloc] init] autorelease];
    [requestsetURL:[NSURLURLWithString:@"http://lib.wap.zol.com.cn/test/login.php"]];
    [requestsetCachePolicy:NSURLRequestUseProtocolCachePolicy];
    [requestsetTimeoutInterval:100.0];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:postData];
   // 应该是application/x-www-form-urlencoded,但对方服务器写成了appliction/x-www-form-urlencoded,告诉服务器是一个表单提交数据方式
    [requestsetValue:@"appliction/x-www-form-urlencoded"forHTTPHeaderField:@"Content-Type"];    
    //得到提交数据的长度
    NSString* len = [NSString stringWithFormat:@"%d", [postData length]];
    //添加一个http包头告诉服务器数据长度是多少
    [requestsetValue:len forHTTPHeaderField:@"Content-Length"];
    [NSURLConnectionconnectionWithRequest:request delegate:self];
}

//POST接收数据方法:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"didReceiveResponse");
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSLog(@"didReceiveData");

    [self.mutabledataappendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"connectionDidFinishLoading");  
    self.strUser = [[NSStringalloc]initWithData:self.mutabledataencoding:NSASCIIStringEncoding];
}
//该片段来自于http://outofmemory.cn

标签:objective-c,网络

收藏

0人收藏

支持

0

反对

0

发表评论