gpt4 book ai didi

android - Android 应用的 token 授权

转载 作者:太空宇宙 更新时间:2023-11-03 11:14:05 25 4
gpt4 key购买 nike

我正尝试在我的 Android 应用程序中使用安全的 Web API。 Web API 使用基本身份验证和使用服务器生成的 token 。我已经能够使用 curl 来使用 Web API,如下所示。

首先,对用户进行身份验证并获取 token 。

curl http://localhost:3000/api/api_keys -u 'user@example.com:UserPassword'

返回 {"token":"0d63b512573dce7be5eb53bab58a5625"}

其次,我使用 token 以经过身份验证的用户身份调用 API。

curl http://localhost:3000/api/exams -H 'Authorization: Token token="0d63b512573dce7be5eb53bab58a5625"'

返回适当的 json 对象。

问题是当我尝试使用下面的代码从 Android 客户端调用 Web API 时,Web API 没有获取 Authorization header ,因此抛出了请求。

...
HttpClient client = new DefaultHttpClient(new BasicHttpParams());
HttpGet httpGet = new HttpGet(targetUrl.toString());
httpGet.setHeader("Content-type", "application/json");
httpGet.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials("test-user@example.com", "Password!"), "UTF-8", false));
httpGet.addHeader("Authorization", "Token token=\"" + getToken() + "\"");

try {
HttpResponse response = client.execute(httpGet);
...

我应该如何向 Web API 验证 Android 应用程序?

最佳答案

您需要先发送请求以获取 token 。然后,您就可以使用 token 了。

关于android - Android 应用的 token 授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19870575/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com