0

我在 Objective C 中创建了一个守护进程,在搜索 USB 设备后,必须向 URL 发送一个 HttpRequest。

我已经通过浏览器进行了尝试,并且可以访问主机。

为了创建一个守护进程,我使用了 Foundation 框架,并尝试使用这种简单的方式创建一个 HTTP 请求:

NSURLRequest *eventRequest = [NSURLRequest requestWithURL:_urlRequest cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20];

self.theConnection=[[NSURLConnection alloc] initWithRequest:eventRequest delegate:self];

if (self.theConnection) {
    self.receivedData = [[NSMutableData data] retain];
} else {
    // Inform the user that the connection failed.
    NSLog(@"Connection Problem");
}

但在这种情况下,我有两个问题:

  1. 请求未发送。
  2. Daemon 结束并且不等待 HttpRequest 的响应。

我怎么解决这个问题?是否存在另一种发出 HTTP 请求并获得响应的方法?

问候。

4

3 回答 3

0

如果您使用的是 NSURLConnection 则发送异步请求并使用委托,

// Create a Request and Connection
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"YOUR URL"]];
NSURLConnection *theConnection= [NSURLConnection connectionWithRequest:request delegate:self];
// Start Request
[theConnection start];

委托方法

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"did fail");
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    NSLog(@"did receive data");
    [self.receivedData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    NSLog(@"did receive response ");
    self.receivedData = [NSMutableData dataWithCapacity:0];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
    NSLog(@"did finish loading");
    [connection release];
}
于 2013-05-10T16:04:29.237 回答
0

使用正常的方式通过 NSURLConnection 框架发送 http 消息不会运行,我尝试使用 CoreFoundation.Framework 来做到这一点:

-(void)implementaZioneChiamata{

for (int i = 0; i < [_arrayOfSerial count]; i++) {

    CFStringRef urlFirst = CFSTR("http://192.168.30.9:88/virtualBadge.aspx?token=");
    CFStringRef token =(CFStringRef)_codicePWD;
    CFStringRef urlSecond = CFSTR("&serial=");
    CFStringRef serial = (CFStringRef) [_arrayOfSerial objectAtIndex:i];
    NSLog(@"URL: %@%@%@%@", urlFirst,token,urlSecond,serial);

    CFStringRef strs[4];

    strs[0] = urlFirst;
    strs[1] = token;
    strs[2] = urlSecond;
    strs[3] = serial;

    CFArrayRef urlArray = CFArrayCreate(kCFAllocatorDefault, (void*)strs, 4, &kCFTypeArrayCallBacks);

    CFStringRef urlCompleta = CFStringCreateByCombiningStrings(kCFAllocatorDefault, urlArray, CFSTR(""));
    NSLog(@"Url Completa: %@",urlCompleta);

    CFURLRef myURL = CFURLCreateWithString(kCFAllocatorDefault, urlCompleta, NULL);
    CFStringRef headerFieldName = CFSTR("host");
    CFStringRef headerFieldValue = CFSTR("192.168.30.9");


    CFStringRef requestMethod = CFSTR("GET");
    CFHTTPMessageRef myRequest =CFHTTPMessageCreateRequest(kCFAllocatorDefault, requestMethod, myURL,
                               kCFHTTPVersion1_1);
      CFHTTPMessageSetHeaderFieldValue(myRequest, headerFieldName, headerFieldValue);
       CFDataRef mySerializedRequest = CFHTTPMessageCopySerializedMessage(myRequest);

    NSString *messReq = [[NSString alloc] initWithData:(NSData*)mySerializedRequest encoding:NSASCIIStringEncoding];

    CFStream


    NSLog(@"Serialized Request: %@", messReq);

}

在代码的第一部分中,我创建了 URL。在此之后,我初始化 CFHTTPMessageRef 以创建 HttpRequest。但现在出现了问题:

一旦我有 HttpMessage 发送它,我需要创建 CFStreamRef 来发送消息。从创建流的想法开始,我如何发送消息?使用 CFStream API?

好的 Guy Tnx 在打开流后寻求帮助,请求是发送添加这样的流。

CFReadStreamRef myReadStream = CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault, myRequest);

CFReadStreamOpen(myReadStream);

全部!

于 2013-05-13T08:02:49.087 回答
0

许多人发现 AFNetworking 框架(来自https://github.com/AFNetworking/AFNetworking的 GIT 克隆)使 HTTP 交互变得更加容易。

具体来说,AFNetworkinggetPath:postPath:方法接受一个path,一个parameters字典,然后是两个块,一个用于success,一个用于failure。像这样

{ [self getPath: @"users"
     parameters: @{ @"api_key" : @"AppAPIKeyForServer" }
        success: ^(AFHTTPRequestOperation *operation, NSDictionary *json) {
          NSArray *users = json[@"users"];
          ....
        }
        failure: ...]; }

创建 AFNetworking 客户端也很容易。您可以创建一个简单的 HTTP 客户端,甚至可以创建 OAuth2 客户端:

@interface MyClient : AFOAuth2Client
@end

- (MyClient *) init
{
  if (self = [super initWithBaseURL: [NSURL URLWithString: kMyClientAPIBaseURLString]
                           clientID: kMyClientOAuth2ClientId
                             secret: kMyClientOAuth2ClientSecret])
  {
    [self registerHTTPOperationClass: [AFJSONRequestOperation class]];
    [self setDefaultHeader: @"Accept"
                     value: @"application/json"];
  }
  return self;
}

至于你的守护进程需要。您应该能够让您的守护进程保留指向 AFNetworking 客户端的指针,然后重复请求。

请注意,OAuth2 客户端位于https://github.com/AFNetworking/AFOAuth2Client

于 2013-05-10T14:14:19.050 回答