使用 POST 而不是 GET 将数据传递给目标 c

Passing data to objective c with POST rather than GET(使用 POST 而不是 GET 将数据传递给目标 c)

本文介绍了使用 POST 而不是 GET 将数据传递给目标 c的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用 url 拦截方法将数据从 javascript 传递到目标 C,方法是将数据作为 url 编码参数传递并使用 NSURLProtocol 拦截请求,但是我现在想要发送大量数据,比如 10,000 个字符长字符串,但这在 GET 请求中似乎并不实际.对吧?

目标 c 有没有办法拦截从 UIWebView 发送的 POST 数据?
如果是这样,我是否仍然使用 NSURLProtocol 以及如何获取 POST 数据?
如果没有,是否有其他方法可以将大量数据从 UIWebView 传递到目标 c?

解决方案

当使用如下代码时:

<上一页>@implementation AppProtocolHandler+ (void)registerSpecialProtocol {静态 BOOL 初始化 = 否;如果(!初始化){初始化=是;[NSURLProtocol registerClass:[AppProtocolHandler 类]];}}- (void)handleRequest {NSURLRequest *request = [自我请求];//通过 app://时为空,但通过 http://时有效NSLog(@"[请求 HTTPBody]: %@", [请求 HTTPBody]);}+ (BOOL)canInitWithRequest:(NSURLRequest *)request {返回是;}+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request {退货请求;}@结尾

对某些协议的请求(例如 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"});

I have been using the url intercept method to pass data from javascript to objective C by passing the data as url encoded parameters and using NSURLProtocol to intercept the request however I am now wanting to send larger amounts of data like say 10,000 character long strings but this does not seem practical to do in a GET request. Right?

Is there a way for objective c to intercept POST data sent from a UIWebView?
If so do I still use NSURLProtocol and how do I get the POST data?
If not is there some other way I can pass larger amounts of data from the UIWebView to objective c?

解决方案

When using code like:

@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

Requests to some protocols (e.g. app://) will result in [request HTTPBody] being null. But if you send through http:// then the [request HTTPBody] will have the request data in an NSData object as expected.

So your Javascript should look something like:

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

And not something like:

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

这篇关于使用 POST 而不是 GET 将数据传递给目标 c的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:使用 POST 而不是 GET 将数据传递给目标 c

基础教程推荐