windows phone 8.1 调用rest api c#

Posted

技术标签:

【中文标题】windows phone 8.1 调用rest api c#【英文标题】:windows phone 8.1 call rest api c# 【发布时间】:2016-07-05 07:24:32 【问题描述】:

我正在开发一个windows phone 8.1 应用程序。在这个应用程序中,我需要调用 restful api。这是我的api调用方法

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?

【问题讨论】:

【参考方案1】:

在错误描述中,它说您没有将名为 System.Net.Http 的程序集添加到您的引用中。只需尝试右键单击应用程序的引用 [图像 1] 并选择 Add reference。在框架列表中找到 System.Net.Http 并将其添加到您的项目中 [图 2]。

[从这里编辑]

因为这不是问题,所以我整理了一个调用 REST API(异步)的方法的小示例。让我知道这是否适合您,如果不适合,请提供有关 API 的更多详细信息。

public async Task<string> callRestAPI(string serviceURL)

    var getRequest = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, serviceURL);

    var postRequest = new System.Net.Http.HttpRequestMessage(HttpMethod.Post, serviceURL);
    postRequest.Content = new StringContent("string data");

    using (var httpClient = new System.Net.Http.HttpClient())
    
        var getResponse = await httpClient.SendAsync(getRequest);
        var postResponse = await httpClient.SendAsync(postRequest);
        var getData = await getResponse.Content.ReadAsStringAsync();
        var postData = await postResponse.Content.ReadAsStringAsync();

        Debug.WriteLine(getData);
        Debug.WriteLine(postData);

        return getData;
    

我在OnNavigatedTo方法中调用该方法只是为了测试如下:

protected override async void OnNavigatedTo(NavigationEventArgs e)

    // TODO: Prepare page for display here.

    // TODO: If your application contains multiple pages, ensure that you are
    // handling the hardware Back button by registering for the
    // Windows.Phone.UI.Input.HardwareButtons.BackPressed event.
    // If you are using the NavigationHelper provided by some templates,
    // this event is handled for you.

    var testResult = await callRestAPI("~your URL here~");

【讨论】:

我的目标是 windows phone 8.1。 感谢您的回复。我尝试过这个。但不工作。给出错误error CS0012: The type 'TaskAwaiter&lt;&gt;' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Threading.Tasks, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. 有些东西似乎很奇怪...您使用的是什么版本的 Visual Studio?您是如何创建项目的? 我正在使用 Visual Studio 2015 Pro。 NewProject -> C# -> windows -> Pivot App(Windows phone 8.1) 据我所知,pivot 应用程序仅适用于 silverlight。那是一个不同的 SDK,因此是错误的。尝试使用 C# -> Windows 8 -> Phone 创建一个项目(或类似的东西,我记不太清了)【参考方案2】:

您必须为 Windows Phone(以及其他平台)添加 Microsoft.Net.Http NuGet 包。您可以在这里找到包裹信息:

https://www.nuget.org/packages/Microsoft.Net.Http/

通过命令行添加或右键单击项目,然后选择Manage NuGet Packages,然后搜索Microsoft.Net.Http,最后选择Install

使用包管理器控制台,您可以使用以下命令将此包添加到您的项目中。

Install-Package Microsoft.Net.Http 

【讨论】:

以上是关于windows phone 8.1 调用rest api c#的主要内容,如果未能解决你的问题,请参考以下文章

Windows phone 8.1 后台任务内存管理

Windows Phone 8.1:向指定用户发送通知

如何在 Windows Phone 8.1 中获取当前位置的当前货币代码

在 Windows 10 移动版上运行的 Windows Phone 8.1 应用程序的后台计时器任务中没有网络

xml 适用于Windows 8.1和Windows Phone 8.1应用程序的扩展器控件演示。

xml 适用于Windows 8.1和Windows Phone 8.1应用程序的扩展器控件的模板。