Cordova:与本地插件共享网络视图cookie



我有一个运行iOS和Android的cordova应用程序,它使用cookie进行身份验证(用户只需键入电子邮件和密码,应用内浏览器设置cookie,后端在Rails中使用设备)。到目前为止,这是有效的。

现在我有一个android和iOS的原生插件,它以后台模式(iOS)/即服务(android)上传一些数据。问题是,插件试图访问的URL也受到保护。因此,插件需要以某种方式将cookie与请求一起发送。

我发现了很多文章,大部分都有点旧(比如这篇http://blog.winfieldpeterson.com/2013/01/17/cookies-in-hybrid-android-apps),每一种解决方案都感觉有点过头了。

我使用的是Cordova 4.3.0,也许有一个标准的解决方案,我还没有找到(自从所有其他文章都写出来后,它得到了更新)。

这是我的Android和iOS代码的一部分,它将数据发送到服务器:

HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
HttpClient httpclient = new DefaultHttpClient();
SchemeRegistry registry = new SchemeRegistry();
SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
registry.register(new Scheme("https", socketFactory, 443));
SingleClientConnManager mgr = new SingleClientConnManager(httpclient.getParams(), registry);
DefaultHttpClient httpClient = new DefaultHttpClient(mgr, httpclient.getParams());
// Set verifier
HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
HttpPost httppost = new HttpPost(locationCache.getUrl());
httppost.setHeader("Content-type", "application/json");
JSONObject body;
body = new JSONObject();
body.put("someKey", "someData");
HttpResponse response = httpclient.execute(httppost);

iOS版本:

NSError * err;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:geodata options:0 error:&err];
NSString * jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSMutableURLRequest *postRequest = [NSMutableURLRequest requestWithURL: [NSURL URLWithString:url]];
postRequest.HTTPMethod = @"POST";
[postRequest setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
postRequest.HTTPBody = [jsonString dataUsingEncoding: NSUTF8StringEncoding];
[NSURLConnection sendAsynchronousRequest:postRequest queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if(error) {
NSLog(@"Httperror: %@, %d", error.localizedDescription, error.code);
} else {
NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"REQUEST SENT TO SERVER! HTTP response code: %d; response body: %@", responseCode, responseString);
}
}];

希望有人能帮忙。

在iOS上,您可以获得如下url的cookie:

NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:@"__YOUR_URL__"]];

或者所有的cookie都是这样的:

NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];

之后,您可以这样设置请求头:

NSDictionary *headers = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
[postRequest setAllHTTPHeaderFields:headers]; 

在安卓系统上,你有webview CookieManager

CookieManager cookieManager=CookieManager.getInstance();
String cookie=cookieManager.getCookie(url);

最新更新