2013-08-27 93 views
1

我試圖使用在https://github.com/robbiehanson/CocoaHTTPServer找到的「CocoaHTTPServer」。我已經添加到我的項目,現在,如果我在我的瀏覽器上鍵入這樣的東西:192.168.3.114:45000我收到一個簡單的歡迎消息索引的HTML頁面(此頁面存儲在默認項目中)。還行吧。它工作正常。我現在需要了解的是,我怎麼可以在瀏覽器上輸入一個簡單的GET請求,例如「192.168.3.114:52000/getElement」,並在瀏覽器上接收一個簡單的字符串。你能給我幫忙嗎?我不知道我可以在哪裏配置或檢查,因爲有一些類。我試圖研究HTTPConnection類,但是我很困惑,因爲我是新的Objective-C編程。 感謝Objective-C/CocoaHttpServer - 試圖用一個參數做一個簡單的GET請求

回答

-1

你可以做一個NSURL請求,然後獲取服務器響應爲一個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 
} 
+0

感謝您的幫助。但是你應該在CocoaHTTPServer中使用這種類型的代碼?你有沒有看到課程? – Hieicker

+0

我想也許我不完全明白你想要完成什麼。你只是想從HTTP服務器返回數據到你的應用程序,或者你的問題是否與你的HTTPServer棧上運行的服務有特定的內涵? – Compy

+0

我有設備內的CocoaHttpServer。當我在瀏覽器中輸入該設備的IP地址(在我的Mac mini中)時,我需要向瀏覽器發送一條簡單消息。目前服務器已經返回一個簡單的html頁面,但我需要修改它,我不知道我該怎麼辦。謝謝 – Hieicker

4

你必須使用一個自定義的HTTPConnection

@interface MyHTTPConnection : HTTPConnection 
... 
@end 

那麼你可以做自定義網址處理

@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以便您的服務器知道您要自己處理連接

[httpServer setConnectionClass:[MyHTTPConnection class]]; 
+0

謝謝@eik!實現代碼現在對我來說很清楚。我對接口MyHTTPConnection:HTTPConnection有一些懷疑。我應該在哪裏添加它?我有修改HTTPConnection.h類嗎? – Hieicker

+0

不,在Xcode中有一個額外的類:「File> New File ...」,「Objective-C class」,並將「Class」設置爲「MyHTTPConnection」(或者任何你喜歡的名字)和「Subclass of」 」。不要忘記在MyHTTPConnection.h中#import「HTTPConnection.h」。 – eik