[英]xamarin forms get call
嘿,我是Xamarin的新手,我正在認真地發現一些基礎知識方面的問題,這確實使我失望。 能否請您幫助我的第一步。 我正在進行get調用,我想返回字符串,但是我有一個'await'運算符只能在async方法內使用。 如何返回我真的沒有xamarin.forms經驗的字符串
public class App : Application
{
public App()
{
// The root page of your application
MainPage = new ContentPage
{
Content = new StackLayout
{
VerticalOptions = LayoutOptions.Center,
Children = {
new Label {
HorizontalTextAlignment = TextAlignment.Center,
Text = "Welcome to Xamarin Forms!"
}
}
}
};
string s = await MakeGetRequest("https://gig.com.qa/AndroidWebService/Services/IPhoneMarketInfo.aspx?id=1");
}
public object DeserializeContent<T>(String stringToDeserialize)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(List<T>));
MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(stringToDeserialize));
return (List<T>)ser.ReadObject(stream);
}
public async Task<string> MakeGetRequest(string url)
{
var request = HttpWebRequest.Create(url);
HttpWebResponse response = await request.GetResponseAsync() as HttpWebResponse;
if (response.StatusCode == HttpStatusCode.OK)
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
var content = reader.ReadToEnd();
if (string.IsNullOrWhiteSpace(content))
{
return response.StatusCode + "Response contained an empty body...";
}
else
{
return content;
}
}
}
else
{
return response.StatusCode.ToString();
}
}
public String SerializeContent(Object objectToSerialize)
{
return JsonConvert.SerializeObject(objectToSerialize);
}
public async Task<string> MakePostRequest(string url, string serializedDataString, bool isJson = true)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
if (isJson)
request.ContentType = "application/json";
else
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
var stream = await request.GetRequestStreamAsync();
using (var writer = new StreamWriter(stream))
{
writer.Write(serializedDataString);
writer.Flush();
writer.Dispose();
}
var response = await request.GetResponseAsync();
var respStream = response.GetResponseStream();
using (StreamReader sr = new StreamReader(respStream))
{
return sr.ReadToEnd();
}
}
protected override void OnStart()
{
// Handle when your app starts
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
}
由於您無法在構造函數中等待,因此最好將其加載到OnStart()中
protected override async void OnStart()
{
string s = await MakeGetRequest("https://gig.com.qa/AndroidWebService/Services/IPhoneMarketInfo.aspx?id=1");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.