通过 NSURLConnection 发送 HTTP GET /HTTP POST 请求
问题:
你可以使用字符串格式来提供参数。
- (void)sendHttpGet{ NSString *urlAsString = @"http://pixolity.com/get.php"; urlAsString = [urlAsString stringByAppendingString:@"?param1=first"]; urlAsString = [urlAsString stringByAppendingString:@"¶m2=second"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlAsString]]; [request setTimeoutInterval:10.0f]; [request setHTTPMethod:@"GET"]; NSOperationQueue *queue = [[NSOperationQueue alloc]init]; [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { if ([data length] >0 && connectionError == nil){ NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"HTML = %@", html); } else if ([data length] == 0 && connectionError == nil){ NSLog(@"Nothing was downloaded."); } else if (connectionError != nil){ NSLog(@"Error happened = %@", connectionError); } }]; }
HTTP POST:
问题:
- (void) sendHttpPost{ NSString *urlAsString = @"http://pixolity.com/post.php"; urlAsString = [urlAsString stringByAppendingString:@"?param1=First"]; urlAsString = [urlAsString stringByAppendingString:@"¶m2=Second"]; NSURL *url = [NSURL URLWithString:urlAsString]; NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url]; [urlRequest setTimeoutInterval:10.0f]; [urlRequest setHTTPMethod:@"POST"]; NSString *body = @"bodyParam1=BodyValue1&bodyParam2=BodyValue2"; [urlRequest setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]]; NSOperationQueue *queue = [[NSOperationQueue alloc]init]; [NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { if ([data length] >0 && connectionError == nil){ NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"HTML = %@", html); } else if ([data length] == 0 && connectionError == nil){ NSLog(@"Nothing was downloaded."); } else if (connectionError != nil){ NSLog(@"Error happened = %@", connectionError); } }]; }
HTTP DELETE:
[urlRequest setTimeoutInterval:30.0f]; [urlRequest setHTTPMethod:@"DELETE"]; NSString *body = @"bodyParam1=BodyValue1&bodyParam2=BodyValue2";
[urlRequest setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
[urlRequest setTimeoutInterval:30.0f]; [urlRequest setHTTPMethod:@"PUT"]; NSString *body = @"bodyParam1=BodyValue1&bodyParam2=BodyValue2"; [urlRequest setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。