タイトルに記載されていることを達成したいのですが、リソースや拷問に関して誰かが私を正しい方向に向けることができますか? HTTP プロトコルの基本は理解していますが、OS X プログラミングに関してはかなり初心者です。
user2559108
質問する
178 次
2 に答える
1
実際、NSMutableURLRequest を使用できます。テストを開始する場合は、次のようにします。
//test.h
#import <Foundation/Foundation.h>
@interface test : NSObject<NSURLConnectionDataDelegate>{
NSMutableData* _responseData;
}
//test.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];
}
この後、ウォズが言ったようにすべてのメソッドを実装する必要がありますが、応答をキャッチします:
#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 に答える