OS X cocoa向PHP页面发送HTTP响应,等待PHP响应请求,继续

时间:2013-07-18 17:45:27

标签: objective-c macos

想要获得标题中提到的内容,是否有人可以指出我在资源或折磨方面的正确方向?我确实理解HTTP协议的基础知识,但我对OS X编程还不熟悉。

2 个答案:

答案 0 :(得分: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];
} 

在此之后你必须像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“你好”;

答案 1 :(得分: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
                               }
                           }];
}