我正在開發一個windows phone 8.1
應用程序。在這個應用程序中,我需要調用寧靜的apis。這裏是我的API調用方法windows phone 8.1 call rest api c#
public static async Task<HttpResponseMessage> callrestApi(string baseurl, string api, string method, string contenttype, object objPost)
{
try
{
HttpResponseMessage response = null;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(baseurl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(contenttype));
switch (method.ToLower())
{
case "get":
// HTTP GET
response = await client.GetAsync(api);
if (response.IsSuccessStatusCode)
{
object obj = await response.Content.ReadAsStringAsync();
//return obj;
}
break;
case "post":
// HTTP POST
response = await client.PostAsync(api, new StringContent(objPost.ToString(), Encoding.UTF8, contenttype));
if (response.IsSuccessStatusCode)
{
object obj = await response.Content.ReadAsStringAsync();
//return obj;
}
break;
default:
break;
}
}
return response;
}
catch (Exception)
{
return null;
}
}
我從調用此方法MainPage.xaml中登錄。我使用用戶名和密碼傳遞json obj。
var resp = await Constants.callrestApi(Constants.base_Url, Constants.apiList.loginApi, Constants.httpmethod.post, Constants.contenttype.json, jsonObj);
if (resp != null)
{
}
當我調試這個我得到以下錯誤
錯誤CS0012:類型「HttpResponseMessage」在未引用的程序集定義。 您必須添加對程序集「System.Net.Http,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b03f5f7f11d50a3a」的引用。
我覺得問題是在await
的調用。我該如何調用restful api?
我針對的是windows phone 8.1。 –
看我的編輯。讓我知道它是否適用於您 – rhcpfan
感謝您的回覆。我嘗試過這個。但不工作。給出錯誤'錯誤CS0012:類型'TaskAwaiter <>'在未引用的程序集中定義。你必須添加一個引用程序集'System.Threading.Tasks,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b03f5f7f11d50a3a'。' –