我真的是Xamarin开发的新手,我只是尝试使用Xamarin.Forms使用共享代码开发Android和iOS应用程序,而我在这里要做的是通过Plugin.RestClient NuGet包从API获取数据。
这是我的MainViewModel。
public MainViewModel(){
InitializeDataAsync();
}
public async Task InitializeDataAsync(){
var employeeServices = new EmployeeServices();
EmployeesList = await employeeServices.getEmployeesAsync();
}
这是我的服务
public async Task<List<Employee>> getEmployeesAsync(){
RestClient<Employee> restClient = new RestClient<Employee>();
var employeeList = await restClient.GetAsync("http://localhost:3000/employee");
return employeeList;
}
这是我的RestClient
public async Task<List<T>> GetAsync(string WebServiceUrl){
var httpClient = new HttpClient();
var json = await httpClient.GetStringAsync(WebServiceUrl);
Debug.WriteLine(WebServiceUrl);
Debug.WriteLine(json);
var taskModels = JsonConvert.DeserializeObject<List<T>>(json);
return taskModels;
}
该代码可以在我的iPhone仿真器上正常工作。我可以在Debug中看到url和json响应。但是,在我的Android模拟器上,列表上没有任何内容。我什至找不到针对url和json响应的调试,我已经检查了我的应用程序输出和设备日志(我使用Xamarin Studio for Mac btw)。
我还已经在我的Android清单中添加了互联网许可。
我该怎么办?
最佳答案
您只能在本地计算机上访问localhost
。您需要将localhost
更改为托管api的计算机的IP地址。
所以api端点
http://localhost:3000/employee
应该是这样的
http://192.168.0.5:3000/employee