【发布时间】:2015-06-15 22:05:29
【问题描述】:
我有一个运行 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);
}
}];
希望有人能提供帮助。
【问题讨论】:
标签: android ios cordova authentication cookies