本文转自 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);
}
庆祝下 庆祝下~~~~