【发布时间】: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