c# - Xamarin Http 请求仅适用于 iOS 模拟器

标签 c# android ios xamarin.forms system.net.httpwebrequest

我正在使用 system.net.http 为我的应用构建网络服务层。我开始在 iphone 模拟器上构建它(因为我首先为 iOS 开发)并且一切正常。我检查了我的代码,然后开始在其他设备上进行测试,但没有任何效果......我在物理 iOS 设备和 android 物理/模拟器上遇到了同样的异常。

我得到的错误是:发送请求时发生错误

下面是我用来发出请求的代码。如果我在代码后面加上断点,那么它会在这一行失败: var responce = await client.SendAsync(request);

public class ApiService : IApiService
{

    HttpClient client;

    public List<Group> Groups { get; private set; }

    public ApiService()
    {
        client = new HttpClient();
        client.MaxResponseContentBufferSize = 256000;
    }

    public async Task<List<Group>> GetGroupsForuser(int userId)
    {

        Groups = new List<Group>();

        //GET http://{server}/groupcontrol/api/group/user/{userId}
        var requestString = string.Format("{0}/{1}/{2}/{3}/{4}/{5}", Constants.BaseUrl, Constants.kControlURL, Constants.kEndpointAPI, Constants.kEndpointOot, Constants.kEndpointUser, userId);
        var requestUri = new Uri(string.Format(requestString, string.Empty));

        //Set method
        var methodName = "GET";
        var httpMethod = new HttpMethod(methodName.ToUpper());

        //Create request
        var request = new HttpRequestMessage(httpMethod, requestUri);

        //Set Headers
        request.Headers.Add("Accept", "application/x-www-form-urlencoded");
        request.Headers.Add("Authorization", new Authorisation().getAuthToken());

        Debug.WriteLine(string.Format("Printing out complete request: {0}", request));

        try
        {

            var responce = await client.SendAsync(request);//client.SendAsync(requestMessage);
            if (responce.IsSuccessStatusCode)
            {
                var content = await responce.Content.ReadAsStringAsync();
                Groups = JsonConvert.DeserializeObject<List<Group>>(content);
            } else {
                Debug.WriteLine(string.Format("{0}",responce.StatusCode));
            }

        }
        catch (Exception ex)
        {
            Debug.WriteLine(">>>ERROR-------------- {0}", ex.Message);
        }

        return Groups;
    }
}

如前所述,代码适用于 iOS 模拟器,但不适用于物理设备(这很奇怪)。我已经更新了 info.plist 以使用任意负载,所以这应该不是问题。我所说的 API 也在 native 生产 iOS 应用程序中使用(我也用 NSURLSession 谈论)所以 API 不是问题,这是一个 xamarin 问题。我还授予了 Android 应用 Internet 权限。

有没有人有这方面的经验?这非常令人沮丧,我不知道如何进一步调试它!

最佳答案

public async Task<string> CallLoginApiAsync(Login login)
{

    client = new HttpClient();
    client.MaxResponseContentBufferSize = 256000;



    var json = JsonConvert.SerializeObject(login, Newtonsoft.Json.Formatting.Indented);


    var content = new StringContent(json, Encoding.UTF8, "application/json");

    var uri = Utils.WebConstants.LOGINURL;
    int tryCount = 0;
    try { 
    while (tryCount <= maxtry)
    {
        var result = await client.PostAsync(uri, content);


        if (result.IsSuccessStatusCode)
        {
            string resultString = await result.Content.ReadAsStringAsync();

            return resultString;


        }
        else
        {
            if (tryCount == maxtry)
            {
                return Utils.AppConstants.ERROR;
            }
            else
            {
                tryCount++;
            }


        }

    }
}
    catch (Exception e)
    {
        return Utils.AppConstants.ERROR;
    }

    return Utils.AppConstants.ERROR;

}

它在 android 中工作。

关于c# - Xamarin Http 请求仅适用于 iOS 模拟器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49234125/

相关文章:

c# - C# 4.5 中协变/逆变不应该允许这样做吗?

c# - C# 函数执行批处理文件的 Git pull 问题

android sherlockActionBar 样式 Action 文本

android - 打开 NavigationView 只点击左上角的图标但不使用 swype 手势

ios - 实现第二个 UICollectionView : could not dequeue a view of kind: UICollectionElementKindCell with identifier xxxx - must register 时出错

ios native 应用程序与 API 或直接数据库连接交谈?

C# vs VB.Net,Shadowing 和 [Overloading (without changing the arguments)] 有什么区别

c# - 使用 "readonly record struct"类型作为方法的out参数,会引起装箱吗?

android - Firebase Crashlytics 不支持 NDK?

ios - 隐式转换丢失浮点精度: 'double' to 'float' ; fix?