IOS4.2网络学习之发送HTTP请求的原理
开发环境 客户端: mac os x 10.6.6 ,ios 4.2 + xcode3.2.5 服务端:windows xp + tomcat6
XCODE代码如下:
- (IBAction) sendHttp : (id) sender{
//此处进行GET方式 发送http请求
//如有中文要进行NSUTF8StringEncoding编码
NSString *urlString =[[NSString stringWithFormat:@"http://192.168.0.110/Login?user=test"
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//初始化http请求,并自动内存释放
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"GET"];
NSString *contentType = [NSString stringWithFormat:@"text/xml"];
[request addValue:contentType forHTTPHeaderField:@"Content-Type"];
NSHTTPURLResponse *urlResponse = nil;
NSError *error = [[NSError alloc] init];
//同步返回请求,并获得返回数据
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
//请求返回状态,如有中文无法发送请求,并且stausCode 值为 0
NSLog(@"response code:%d",[urlResponse statusCode]);
if([urlResponse statusCode] >= 200 && [urlResponse statusCode] <300){
NSLog(@"response:%@",result);
}
}
服务端:
1.设置TOMCAT启动参数 -Dfile.encoding=UTF-8
2.编写简单的LoginServlet,并在web.xml作好配置
注:如果不设置TOMCAT启动时的编码参数,接收到的result为NULL.
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/10531/viewspace-710168/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/10531/viewspace-710168/