我一直在使用URL拦截方法将数据从JavaScript传递到目标C,通过将数据作为URL编码参数传递并使用NSURLProtocol来拦截请求,但是我现在想发送更大量的数据,例如说10,000个字符长字符串,但是这是这样在GET请求中似乎不实用。正确的?

目标C有没有办法拦截从UIWebView发送的帖子数据?
如果是这样,我仍然使用NsurlProtocol,如何获取帖子数据?
如果没有,我可以将大量数据从UIWebView传递到目标C?

有帮助吗?

解决方案

使用类似代码时:

@implementation AppProtocolHandler

+ (void)registerSpecialProtocol {
    static BOOL inited = NO;

    if (!inited) {
        inited = YES;
        [NSURLProtocol registerClass:[AppProtocolHandler class]];
    }
}

- (void)handleRequest {
    NSURLRequest *request = [self request];

    // null when via app:// but works when via http://
    NSLog(@"[request HTTPBody]: %@", [request HTTPBody]);
}

+ (BOOL)canInitWithRequest:(NSURLRequest *)request {
    return YES;
}

+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request {
    return request;
}

@end

请求某些协议(例如 app://)将导致 [request HTTPBody] 存在 null. 。但是如果您发送 http:// 然后 [request HTTPBody] 将在一个中有请求数据 NSData 对象如预期。

因此,您的JavaScript应该看起来像:

$.post("http://test/hello/world", {'data':"foo bar"});

不是 就像是:

$.post("app://test/hello/world", {'data':"foo bar"});

其他提示

任何请求都将被委托拦截,因此您可以发送任何邮政ajax请求,填写所需的参数和值,然后发送。所有值将被拦截,您可以按照到目前为止的方式使用它们。可以使用jQuery发送简单的帖子请求,例如:

$ .post(“ toobjc.html”,{'data':“ 10k字符long string eft in there ...”});

更多这里: http://api.jquery.com/jquery.post/

您绝对应该使用帖子。您只需要为其设置请求即可。您可能需要确保数据编码并处理其他几个详细信息。

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:myMimeType forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", requestData.length]       
         forHTTPHeaderField:@"Content-Length"];

[request setHTTPBody:requestData];

[self.playerView loadRequest: request];

另外,您可以发送多部分文档或表单值。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top