问题
I'm trying to use the "CocoaHTTPServer" found at https://github.com/robbiehanson/CocoaHTTPServer. I have added it to my project, and now, if i type on my browser something like this: 192.168.3.114:45000 i receive an html page called index with a simple welcome message (this page is stored inside the default project). This is ok. It works correctly. What i need to understand now, is how can i for example do a simple GET request typing on the browser something like "192.168.3.114:52000/getElement" and receive on the browser a simple String. Can you please give me help? I don't know where i can configure or check this because there are some classes. I'm trying to study the HTTPConnection class but i'm going in confusion because i'm new on the objective-c programming. Thanks
回答1:
You have to use a custom HTTPConnection
subclass
@interface MyHTTPConnection : HTTPConnection
...
@end
then you could do custom URL handling
@implementation MyHTTPConnection
- (NSObject<HTTPResponse> *)httpResponseForMethod:(NSString *)method URI:(NSString *)path
{
HTTPLogTrace();
if ([path isEqualToString:@"/getElement"])
{
NSData *data = ...
HTTPDataResponse *response = [[HTTPDataResponse alloc] initWithData:data];
return response;
}
// default behavior for all other paths
return [super httpResponseForMethod:method URI:path];
}
@end
and the set HTTPServer connectionClass
so that your server knows you want to handle the connections yourself
[httpServer setConnectionClass:[MyHTTPConnection class]];
回答2:
You can do an NSURL request and then get the server response as an NSString:
NSString *URL = @"http://yoururlhere.com?var1=";
URL = [URL stringByAppendingString: yourvarstring];
NSData *dataURL = [NSData dataWithContentsOfURL: [ NSURL URLWithString: URL]];
NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];
//Check if the server has any output
if([serverOutput length] == 0)
{
//Do something
} else {
//Do Something else
}
来源:https://stackoverflow.com/questions/18462937/objective-c-cocoahttpserver-trying-to-do-a-simple-get-request-with-one-paramet