我下载了 Google Endpoints Tic Tac Toe 示例 - Java 中的服务器代码。
为了快速运行它,我从 API 定义中删除了 clientId,这样我就可以快速看到它在 API Explorer 中运行:
@Api(name = "tictactoe", version = "v1")
public class ScoresV1
{
...
我可以使用 API Explorer 运行以下方法,打开 OAuth 并使用我的 Gmail 帐户进行身份验证。我可以在调试器中看到设置为该帐户的“用户”对象:
@ApiMethod(name = "scores.list")
@SuppressWarnings("unchecked")
public List<Score> list(@Nullable @Named("limit") String limit,
@Nullable @Named("order") String order, User user)
throws OAuthRequestException, IOException
{
...
然后我继续生成 Android 客户端(clientId 仍被删除)。我还下载了官方安卓应用程序获取 UI 类和 res 文件(帐户选择器和游戏界面)。
这就是我被困住的地方。当在真实的 Android 设备上运行时,TictactoeActivity 中的以下代码抛出了 GoogleAuthIOException:
@Override
protected ScoreCollection doInBackground(Void... unused)
{
ScoreCollection scores = null;
try
{
scores = service.scores().list().execute();
}
catch (IOException e)
{
e.printStackTrace();
这是例外情况:
02-21 16:38:47.051: D/TicTacToe(6151): com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAuthIOException
02-21 16:38:47.051: D/TicTacToe(6151): at com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential$RequestHandler.intercept(GoogleAccountCredential.java:286)
02-21 16:38:47.051: D/TicTacToe(6151): at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:858)
...
进一步深入研究源代码,我发现 GoogleAuthUtil.getToken() 中的这段代码引发了根异常,这有点无济于事:
com.google.android.gms.auth.GoogleAuthException: Unknown
现在,我在本地开发服务器上的 ScoreV1.list() 处设置了一个断点,在使用 API Explorer 进行测试时命中了该断点,但 Android 客户端甚至没有命中服务器就失败了。现在,在本地开发服务器上设置“-a 0.0.0.0”以接受传入连接。我已经检查过该 URL 也正确,并且我可以从手机运行以下 URL
Chrome 浏览器(由于没有设置用户,它给了我一个身份验证错误,但没关系):
http://192.168.2.23:8888/_ah/api/tictactoe/v1/score?limit=1&order=1
所以我知道网络正在运行并且手机可以访问它。我还验证了 AndroidManifest.xml 具有以下权限集:
<uses-sdk android:minSdkVersion="14" android:targetSdkVersion="14"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
下面的代码显示了 TicTacToe.java 中的 URL 和路径:
public static final String DEFAULT_ROOT_URL = "http://192.168.2.23:8888/_ah/api/";
/**
* The default encoded service path of the service. This is determined when
* the library is generated and normally should not be changed.
*
* @since 1.7
*/
public static final String DEFAULT_SERVICE_PATH = "tictactoe/v1/";
/**
* The default encoded base URL of the service. This is determined when the
* library is generated and normally should not be changed.
*/
public static final String DEFAULT_BASE_URL = DEFAULT_ROOT_URL
+ DEFAULT_SERVICE_PATH;
...
现在,真正让我困惑的是,即使我将 DEFAULT_ROOT_URL 更改为随机的内容(例如 5.5.5.5),我也会得到完全相同的 GoogleAuthIOException!当主机无法访问时,我希望得到不同的异常......
另外,我尝试将服务器部署到生产环境,并将 URL 重新指向 [myapp].appspot.com 地址 - 结果相同。服务器日志从未记录传入的请求。
事实上,我现在真的陷入困境了。请帮忙!太感谢了!!!