读书人

iPhoneHttp通讯

发布时间: 2012-06-29 15:48:46 作者: rapoo

iPhoneHttp通信

1、准备阶段

#import "HttpUtil.h"@implementation HttpUtil-(NSString *)httpGet:(NSString *)httpUrl{ NSMutableURLRequest *request =[[NSMutableURLRequest alloc] init]; [request setURL:[NSURL URLWithString:httpUrl]]; [request setHTTPMethod:@"GET"]; // NSString *contentType = [NSString stringWithFormat:@"text/xml"]; NSString *contentType = [NSString stringWithFormat:@"application/x-www-form-urlencoded"];[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]; return result;}-(NSString *)httpPost:(NSString *)httpUrl:(NSString *)postData{ NSMutableURLRequest *request =[[NSMutableURLRequest alloc] init]; [request setURL:[NSURL URLWithString:httpUrl]]; [request setHTTPMethod:@"POST"]; NSString *contentType = [NSString stringWithFormat:@"application/x-www-form-urlencoded"]; [request addValue:contentType forHTTPHeaderField: @"Content-Type"]; NSMutableData *postBody = [NSMutableData data]; [postBody appendData:[[NSString stringWithFormat:postData] dataUsingEncoding:NSUTF8StringEncoding]]; [request setHTTPBody:postBody]; 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]; return result;}@end

?<!--EndFragment-->

读书人网 >Iphone

热点推荐