我正在尝试使用 HttpURLConnection 已经有一段时间了,我尝试了在这里和其他地方发布的几个解决方案,但似乎没有任何效果。
我有以下架构:
- Ruby on Rails Web 服务(带有 JSON 的 Rest 接口)
- 带有 RestKit 的 iPhone 客户端
- 带有 HttpURLConnection 的 Android 客户端
iPhone 客户端就像一个魅力。它使用 RestKit 连接到 Web 服务。
现在,Android 客户端完全不同了。我总是从服务器收到 401 Unauthorized 消息(这会导致本地 FileNotFoundException)。
奇怪的是,iPhone 客户端得到了同样的错误,但是 RestKit 以某种方式通过再次发送相同的请求来管理它。我当然试过了,但我只是两次得到同样的错误。
在 Rails 日志输出中,它看起来像这样:
Started POST "/api/v1/login" for 127.0.0.1 at 2012-05-03 12:44:56 +0200
Processing by Api::V1::ApiController#session_login as JSON
Parameters: {"device"=>{"model"=>"Simulator", "system"=>"Android", "version"=>"Hugo", "name"=>"Android Simulator"}, "email"=>"florian.letz@simpliflow.com", "api"=>{"device"=>{"model"=>"Simulator", "system"=>"Android", "version"=>"Hugo", "name"=>"Android Simulator"}, "email"=>"florian.letz@simpliflow.com", "action"=>"session_login", "controller"=>"api/v1/api"}}
Filter chain halted as :require_login_from_http_basic rendered or redirected
Completed 401 Unauthorized in 0ms (ActiveRecord: 0.0ms)
当 iPhone 客户端连接时会出现完全相同的消息,但随后突然出现一个神奇的第二个请求并通过。
在 Android 客户端上,我执行以下操作:
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod(HTTP_POST);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Accept-Encoding", "gzip, deflate");
String userpassword = email + ":" + password;
con.setRequestProperty("Authorization", "Basic " + new String(Base64.encodeBase64(userpassword.getBytes())));
String body = jsonLogin.toString();
byte[] body_bytes = body.getBytes();
con.setRequestProperty("Content-Length", "" + Integer.toString(body_bytes.length));
con.setRequestProperty("Content-Language", "en-US");
con.setInstanceFollowRedirects(false);
con.setUseCaches (false);
con.setDoInput(true);
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream (con.getOutputStream ());
wr.write(body_bytes);
wr.flush ();
wr.close ();
InputStream is = con.getInputStream();
最后一行发生异常。
我已经阅读了一些关于重定向的内容,但是在服务器上没有实现重定向,我在客户端也没有收到重定向。我刚收到 401 Unauthorized。Web 服务和 iphone 客户端中的代码表明了一个非常简单的工作流程。只需发送数据并接收答案。当 iPhone 连接时,我不知道 SECOND 登录呼叫来自哪里。
这里有人知道问题可能是什么吗?
非常感谢!
编辑#1:我已经确定了“神奇”的第二个请求。RestKit 日志显示以下内容:
Asked if canAuthenticateAgainstProtectionSpace: with authenticationMethod = NSURLAuthenticationMethodDefault
然后这会导致第二个请求带有很多我无法理解的标头。
那么您知道在 Android 中实现此功能的方法吗?