Ped*_*sta 2 c# android httpwebrequest xamarin
我正在尝试使用Xamarin开发适用于Android的简单应用。该应用向Web API发出HTTP请求。
这是主要代码:
var messageTxt = FindViewById<EditText>(Resource.Id.message);
var apiUrlTxt = FindViewById<EditText>(Resource.Id.apiurl);
var url = String.Format("{0}/api/values/{1}", apiUrlTxt.Text, messageTxt.Text);
var j = await FetchApi(url);
var apiReturn = FindViewById<TextView>(Resource.Id.apiReturn);
apiReturn.Text = j;
Run Code Online (Sandbox Code Playgroud)
这是FetchApi方法:
private async Task<string> FetchApi(string url)
{
try
{
var request = HttpWebRequest.Create(url);
request.ContentType = "application/json";
request.Method = "GET";
request.Timeout = 10000;
using (var response = await request.GetResponseAsync())
{
using (var s = response.GetResponseStream())
{
return await Task.Run(() => JsonObject.Load(s));
}
}
}
catch(Exception ex)
{
return await Task.Run(() => "Erro - " + ex.Message);
}
}
Run Code Online (Sandbox Code Playgroud)
我正在外部设备上运行该应用程序。一切在Debug模式下都可以正常工作,但是当我切换到Release时,HttpWebRequest返回一个WebException,消息为“错误: ConnectFailure (访问被拒绝)”。
我已经尝试过将Debug和Release模式的Packaging和Linker选项设置为相同,但是Debug版本继续工作,而Release版本继续失败。
我还尝试在“发布”模式下将“链接”设置为“无”,但是它也没有用。
我在这里想念什么吗?
您需要通过在AndroidManifest.xml中设置标志来明确告知Android您的应用可以访问Internet 。当您处于调试模式时,默认情况下会启用此功能,但是在发行版中,您需要对其进行专门设置。
| 归档时间: |
|
| 查看次数: |
1082 次 |
| 最近记录: |