我想实现标题中提到的内容,有人能指出我关于资源或酷刑的正确方向吗?我确实了解 HTTP 协议的基础知识,但我对 OS X 编程相当陌生。
user2559108
问问题
178 次
2 回答
1
事实上你可以使用 NSMutableURLRequest,如果你想做一个测试开始你可以这样做:
//test.h
#import <Foundation/Foundation.h>
@interface test : NSObject<NSURLConnectionDataDelegate>{
NSMutableData* _responseData;
}
//测试.m
@implementation test
//Just call this method to start the request.
-(void)testRequest{
//set request
NSURL url = [NSURL URLWithString:@"http://ip/file.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLCacheStorageNotAllowed
timeoutInterval:20.0];
//Start the request
NSURLConnection * connection;
connection = [[NSURLConnection alloc] initWithRequest: request delegate:self];
}
在此之后,您必须实现 woz 所说的所有方法,但要捕获响应:
#pragma mark - NSURLConectionDlegate Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
_responseData = [[NSMutableData alloc] init];
}
//Receive data from the server
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// Append the new data to the instance variable
[_responseData appendData:data];
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
willCacheResponse:(NSCachedURLResponse*)cachedResponse {
// Return nil to indicate not necessary to store a cached response for this connection
return nil;
}
//in this method you can check the response.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// The request is complete and data has been received
NSString *receivedDataString = [[NSString alloc] initWithData:_responseData encoding:NSUTF8StringEncoding];
NSLog(@"this is reponse: %@",receivedDataString);
}
服务器端
//file.php
echo "hello";
于 2013-07-18T18:51:44.497 回答
0
我喜欢简短的解决方案,并使用块。
- (void)sendRequestWithURL:(NSURL*) url {
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (!error) {
NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}
else {
///log error
}
}];
}
于 2013-07-18T19:12:24.760 回答