我使用vs2015,webapi网络服务和xamarin.Android
我创建了一个包含2个项目的解决方案
1-项目是web Api 2-是xamarin.android项目
在Web API项目中我有一个Url(http://localhost:27635/api/books/1/details) 这回复了这本书的详细信息
{"query":{"Title":"Midnight Rain","Genre":"Fantasy","PublishDate":"2000-12-16T00:00:00","Description":"A former architect battles an evil sorceress.","Price":14.95,"Author":"Ralls, Kim"}}
"}
并在xamarin项目中: 我使用此代码来使用web api项目 公共类MainActivity:活动 {
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
:
Button button = FindViewById<Button>(Resource.Id.getWeatherButton);
// When the user clicks the button ...
button.Click += async (sender, e) => {
// Get the latitude and longitude entered by the user and create a query.
string url = "http://localhost:8080/api/books/1/details";
//string url = "http://169.254.129.9/api/books/1/details";
// Fetch the information asynchronously,
// parse the results, then update the screen:
JsonValue json = await FetchWeatherAsync(url);
ParseAndDisplay(json);
};
}
// Gets data from the passed URL.
private async Task<JsonValue> FetchWeatherAsync(string url)
{
// Create an HTTP web request using the URL:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
request.ContentType = "application/json";
request.Method = "GET";
// Send the request to the server and wait for the response:
using (WebResponse response = await request.GetResponseAsync())
{
// Get a stream representation of the HTTP web response:
using (Stream stream = response.GetResponseStream())
{
// Use this stream to build a JSON document object:
JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));
Console.Out.WriteLine("Response: {0}", jsonDoc.ToString());
// Return the JSON document:
return jsonDoc;
}
}
}
// Parse the weather data, then write temperature, humidity,
private void ParseAndDisplay(JsonValue json)
{
TextView location = FindViewById<TextView>(Resource.Id.locationText);
JsonValue weatherResults = json["query"];
location.Text = weatherResults["Title"];
}
}
当我使用我的本地webapi项目时,下面的代码将不会被执行,并且本地webservice无法连接到Android模拟器以从Web服务获取数据,并且给我一个错误
using (Stream stream = response.GetResponseStream())
{
// Use this stream to build a JSON document object:
JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));
Console.Out.WriteLine("Response: {0}", jsonDoc.ToString());
// Return the JSON document:
return jsonDoc;
}
但是,当我使用外部网络api工作正常时