有没有人试图为GET请求实现处理程序(POST方法的问题),而不使用包含的(和酷的)GCDWebUploader?
我需要服务器响应将文件上传到客户端的GET请求http://local/download/filename.ext
。
我正在将请求符合代码" BackgroundSessionManager" (可在此处获取:AFNetworking 2.0 and background transfers)并且无需担心即可发送和触发。
我正在获取服务器端的日志:
[DEBUG] Did start background task
[DEBUG] Connection received 248 bytes on socket 14
[DEBUG] Connection on socket 14 preflighting request "GET /download/file.ext with 248 bytes body
[DEBUG] Connection on socket 14 processing request "GET /download/file.ext" with 248 bytes body
[EXCEPTION] *** +[NSJSONSerialization dataWithJSONObject:options:error:]: value parameter is nil
[DEBUG] Did close connection on socket 14
我无法弄清楚如何设置处理程序,以便不关心从JSON解析的不存在的查询。
[webServer addHandlerForMethod:@"GET" path:@"/download" requestClass:[GCDWebServerRequest class] processBlock:^GCDWebServerResponse *(GCDWebServerRequest* request) {
__strong AppDelegate* strongSelf = weakSelf;
NSLog(@"request for download is %@", request);
return [strongSelf downloadFile:request];
}];
答案 0 :(得分:3)
我删除了此代码以使其正常工作:
/*
// Add a handler to respond to GET requests
[webServer addDefaultHandlerForMethod:@"GET"
requestClass:[GCDWebServerRequest class]
asyncProcessBlock:^(GCDWebServerRequest* request, GCDWebServerCompletionBlock completionBlock) {
__strong AppDelegate* strongSelf = weakSelf;
.....
*/
[webServer addHandlerForMethod:@"GET" path:@"/download" requestClass:[GCDWebServerRequest class] processBlock:^GCDWebServerResponse *(GCDWebServerRequest* request) {
__strong AppDelegate* strongSelf = weakSelf;
NSLog(@"request for download is %@", request);
return [strongSelf downloadFile:request];
}];
无论如何,注释掉了接管并期待JSON数据包的默认处理程序。
<强>更新强>
要使用GCDWebServer和NSURLSessions实现后台文件传输(即使使用AFNetworking),最好的方法是使用MatchBlock实例化GET处理程序,如下所示:
[webServer addHandlerWithMatchBlock:^GCDWebServerRequest *(NSString* requestMethod, NSURL* requestURL, NSDictionary* requestHeaders, NSString* urlPath, NSDictionary* urlQuery) {
if (![requestMethod isEqualToString:@"GET"]) {
return nil;
}
if (![urlPath hasPrefix:@"/download"]) {
return nil;
}
return [[GCDWebServerRequest alloc] initWithMethod:requestMethod url:requestURL headers:requestHeaders path:urlPath query:urlQuery];
} processBlock:^GCDWebServerResponse *(GCDWebServerRequest* request) {
GCDWebServerResponse* response = nil;
NSString* filePath = [[weakSelf applicationDocumentsDirectory] stringByAppendingPathComponent:[[request.path stringByRemovingPercentEncoding]];
NSString* fileType = [[[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:NULL] fileType];
if (fileType) {
if ([fileType isEqualToString:NSFileTypeRegular]) {
// always allow ranges in our requests
response = [GCDWebServerFileResponse responseWithFile:filePath byteRange:request.byteRange];
[response setValue:@"bytes" forAdditionalHeader:@"Accept-Ranges"];
}
}
if (response) {
response.cacheControlMaxAge = 360;
} else {
response = [GCDWebServerResponse responseWithStatusCode:kGCDWebServerHTTPStatusCode_NotFound];
}
return response;
}];