向 api 发布请求适用于 Android,但不适用于 IOS.沙马林 [英] Post request to api works for Android but not for IOS. Xamarin

查看:21
本文介绍了向 api 发布请求适用于 Android,但不适用于 IOS.沙马林的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试创建一个函数来验证我的令牌,它适用于 Android 但不适用于 IOS.来自我的自定义 API 的 IOS 响应返回 401 未经授权(当您发送无效密钥时应该这样做),但我已经在邮递员中尝试过该密钥并且它是有效的.

I've been trying to create a function that validates my token and it works for Android but not for IOS. The response on IOS from my custom API returns 401 unauthorized (which it should when you send an invalid key), but I've tried the key in postman and it's valid.

也许这与格式有关?但我不明白 Android 和 IOS 之间有什么区别.

Maybe this has something to do with formatting? But I don't see what would be the difference between Android and IOS.

一些代码:

public async Task<T> PostResponse<T>(string weburl, string jsonstring) where T : class
    {
        var Token = App.TokenDatabase.GetToken();
        string ContentType = "application/json";
        var token = string.Format("Token token={0}", Token.access_token);
        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);

        try
        {
            var result = await client.PostAsync(weburl, new StringContent(jsonstring, Encoding.UTF8, ContentType));
            if(result.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var JsonResult = result.Content.ReadAsStringAsync().Result;
                try
                {
                    var ContentResp = JsonConvert.DeserializeObject<T>(JsonResult);
                    return ContentResp;
                }
                catch { return null; }

            }

        }
        catch { return null;  }
        return null;
    }

我在服务器端创建了一些日志,当我运行 IOS 应用程序时,由于某种原因,令牌没有传递到服务器.

I've created some logs on the server side and when I run the IOS app the token doesn't get passed on to the server for some reason.

PHP 代码:

$token = null;
$headers = apache_request_headers();
if(isset($headers['Authorization'])){
  $matches = array();
  preg_match('/Token token=(.*)/', $headers['Authorization'], $matches);
  if(isset($matches[1])){
    $token = $matches[1];
  }
} 

file_put_contents('../config/log.txt', $token);

我已检查应用程序是否发送了令牌.它在途中的某个地方消失了.

I've checked that the app sends the token. It disappears somewhere on the way.

经过一些日志记录后,我发现令牌在通过 IOS 发送时位于标头中但不在授权标头中,您如何解决此问题?

After some logging, I found out that the token is in the header but not in the Authorization header when sent through IOS, how do you solve this?

推荐答案

我通过下载 Flurl 和 Flurl.Http 插件解决并添加了这一行:

I solved it by downloading Flurl and Flurl.Http plugins and added this line:

 var result = await url.WithOAuthBearerToken(token).PostJsonAsync(jsonstring);

信用:Xamarin 表单未发送授权标头

还有

流畅的 HTTP

这篇关于向 api 发布请求适用于 Android,但不适用于 IOS.沙马林的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆