【问题标题】:Xamarin Http Requests only work on iOS SimulatorXamarin Http 请求仅适用于 iOS 模拟器
【发布时间】:2018-03-12 11:29:00
【问题描述】:

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

我得到的错误是:An error occurred while sending the request

下面是我用来发出请求的代码。如果我按照带有断点的代码,那么它将在这一行失败: 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 也被用于原生生产 iOS 应用程序(我也与 NSURLSession 交谈)所以 API 不是问题,这是一个 xamarin 问题。我还给了Android应用Internet权限。

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

【问题讨论】:

  • 您是否为 Android 添加了权限?
  • @VolkanSahin45 是

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


【解决方案1】:
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;

}

它在安卓中运行。

【讨论】:

    【解决方案2】:

    所以我将失败的请求从try 块中取出,以便进一步调试。我发现问题与证书签名和我用来与应用程序对话的地址有关。

    首先,Android 不喜欢真实地址并要求 IP(谢谢大家)。我需要禁用证书检查的第二件事,我使用以下代码执行此操作:

    System.Net.ServicePointManager.ServerCertificateValidationCallback +=
    (sender, cert, chain, sslPolicyErrors) =>
    {
        if (cert != null) System.Diagnostics.Debug.WriteLine(cert);
        return true;
    };
    

    我把它放在我的请求之前,它现在可以在所有设备上使用。 Xamarin 再次来袭! :D

    【讨论】:

      猜你喜欢
      • 2020-04-10
      • 1970-01-01
      • 2013-07-19
      • 2020-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多