/**
* url:請求地址
* verb:請求方式
* parameters:請求參數
*/
+(NSString *)sendRequestTo:(NSURL *)url usingVerb:(NSString *)verb withParameters:(NSDictionary *)parameters{
NSString *jsonStr = nil;
NSData *body = nil;
NSMutableString *params = nil;
NSString *contentType = @"text/html; charset=utf-8";
NSURL *finalURL = url;
if(nil != parameters){
params = [[NSMutableString alloc] init];
for(id key in parameters){
NSString *encodedkey = [key stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
CFStringRef value = (CFStringRef)[[parameters objectForKey:key] copy];
CFStringRef encodedValue = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, value,NULL,(CFStringRef)@";/?:@&=+$", kCFStringEncodingUTF8);
[params appendFormat:@"%@=%@&", encodedkey, encodedValue];
CFRelease(value);
CFRelease(encodedValue);
}
[params deleteCharactersInRange:NSMakeRange([params length] - 1, 1)];
}
//
if([verb isEqualToString:@"POST"]){
contentType = @"application/x-www-form-urlencoded; charset=utf-8";
body = [params dataUsingEncoding:NSUTF8StringEncoding];
}else{
if(nil != parameters){
NSString *urlWithParams = [[url absoluteString] stringByAppendingFormat:@"?%@", params];
finalURL = [NSURL URLWithString:urlWithParams];
}
}
NSMutableDictionary *headers = [[[NSMutableDictionary alloc] init] autorelease];
[headers setValue:contentType forKey:@"Content-Type"];
[headers setValue:@"text/html" forKey:@"Accept"];
[headers setValue:@"no-cache" forKey:@"Cache-Control"];
[headers setValue:@"no-cache" forKey:@"Pragma"];
[headers setValue:@"close" forKey:@"Connection"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:finalURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:verb];
[request setAllHTTPHeaderFields:headers];
if(nil != parameters){
[request setHTTPBody:body];
}
[params release];
//
NSURLResponse *response;
NSError *error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if(error){
NSLog(@"something is wrong: %@", [error description]);
}else{
if(responseData){
jsonStr = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
}
}
return jsonStr;
}
+(void)testRequest{
NSLog(@"test request...");
NSString *getUrl = @"http://192.168.222.1:8080/vgirl/isVgirl.php";
NSString *postUrl = @"http://192.168.222.1:8080/vgirl/isVgirlByPost.php";
NSMutableDictionary *dlist = [[NSMutableDictionary alloc] init];
[dlist setObject:@"pig" forKey:@"uid"];
[dlist setObject:@"access token" forKey:@"AccessToken"];
[dlist setObject:@"access token secret" forKey:@"AccessTokenSecret"];
NSString *jsonStrGet = [NetAPI sendRequestTo:[NSURL URLWithString:getUrl] usingVerb:@"GET" withParameters:dlist];
NSLog(@"do get: jsonStrGet = %@", jsonStrGet);
NSString *jsonStrPost = [NetAPI sendRequestTo:[NSURL URLWithString:postUrl] usingVerb:@"POST" withParameters:dlist];
NSLog(@"do post: jsonStrPost = %@", jsonStrPost);
[dlist release];
}
摘自 與時俱進