便携式类库HttpClient

  发布于 2023-01-07 15:32

对于我的一个项目,我想开发一个可以在不同平台(桌面,移动,表面等)中使用的库.因此选择了Porable Class Library.

我正在使用HttpClient开发一个用于调用不同API调用的类.我坚持如何调用方法,响应和解决方法.这是我的代码: -

    public static async Task ExecuteGet(string uri)
    {
        using (HttpClient client = new HttpClient())
        {
            // TODO - Send HTTP requests
            HttpRequestMessage reqMsg = new HttpRequestMessage(HttpMethod.Get, uri);
            reqMsg.Headers.Add(apiIdTag, apiIdKey);
            reqMsg.Headers.Add(apiSecretTag, ApiSecret);
            reqMsg.Headers.Add("Content-Type", "text/json");
            reqMsg.Headers.Add("Accept", "application/json");

            //response = await client.SendAsync(reqMsg);
            //return response;

            //if (response.IsSuccessStatusCode)
            //{
                string content = await response.Content.ReadAsStringAsync();
                return (JObject.Parse(content));
            //}
        }
    }

    // Perform AGENT LOGIN Process
    public static bool agentStatus() {
        bool loginSuccess = false;

        try
        {
            API_Utility.ExecuteGet("http://api.mintchat.com/agent/autoonline").Wait();
            // ACCESS Response, JObject ???
        }
        catch
        {
        }
        finally
        {
        }

像ExecuteGet一样,我也会为ExecutePost创建.我的查询来自ExecuteGet,如果(1)我在解析时只传递了JObject,只有IsSuccessStatusCode,那么我怎么知道任何其他错误或消息来通知用户.(2)如果我通过了响应,那么我该如何在此处进行分配

response = API_Utility.ExecuteGet("http://api.mintchat.com/agent/autoonline").Wait();  

这是错误的.

处理这种情况的最佳方法是什么?我必须调用多个API,因此不同的API将具有不同的结果集.

此外,您能否确认以这种方式设计并添加PCL参考我将能够在多个项目中访问.

更新: - 如下面的2个答案所述,我更新了我的代码.正如提供的链接中所提到的,我正在调用另一个项目.这是我的代码: -

便携式班级图书馆: -

    private static HttpRequestMessage getGetRequest(string url)
    {
        HttpRequestMessage reqMsg = new HttpRequestMessage(HttpMethod.Get, url);
        reqMsg.Headers.Add(apiIdTag, apiIdKey);
        reqMsg.Headers.Add(apiSecretTag, ApiSecret);
        reqMsg.Headers.Add("Content-Type", "text/json");
        reqMsg.Headers.Add("Accept", "application/json");

        return reqMsg;
    }

    // Perform AGENT LOGIN Process
    public static async Task agentStatus() {
        bool loginSuccess = false;
        HttpClient client = null;
        HttpRequestMessage request = null;

        try
        {
            client = new HttpClient();
            request = getGetRequest("http://api.mintchat.com/agent/autoonline");
            response = await client.SendAsync(request).ConfigureAwait(false);

            if (response.IsSuccessStatusCode)
            {
                string content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                JObject o = JObject.Parse(content);
                bool stat = bool.Parse(o["status"].ToString());

                ///[MainAppDataObject sharedAppDataObject].authLogin.chatStatus = str;
                o = null;
            }
            loginSuccess = true;

        }
        catch
        {
        }
        finally
        {
            request = null;
            client = null;
            response = null;
        }

        return loginSuccess;
    }

从另一个WPF项目,在一个btn点击事件中,我称之为: -

    private async void btnSignin_Click(object sender, RoutedEventArgs e)
   {
         /// Other code goes here
         // ..........

            agent = doLogin(emailid, encPswd);
            if (agent != null)
            {
                //agent.OnlineStatus = getAgentStatus();

                // Compile Error at this line
                bool stat = await MintWinLib.Helpers.API_Utility.agentStatus();

                ... 

我收到这4个错误: -

Error   1   Predefined type 'System.Runtime.CompilerServices.IAsyncStateMachine' is not defined or imported D:\...\MiveChat\CSC 
Error   2   The type 'System.Threading.Tasks.Task`1' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Threading.Tasks, Version=1.5.11.0, Culture=neutral, PublicKeyToken=b03f5f7f89d50a3a'.   D:\...\Login Form.xaml.cs   97  21  
Error   3   Cannot find all types required by the 'async' modifier. Are you targeting the wrong framework version, or missing a reference to an assembly?   D:\...\Login Form.xaml.cs   97  33  
Error   4   Cannot find all types required by the 'async' modifier. Are you targeting the wrong framework version, or missing a reference to an assembly?   D:\...\Login Form.xaml.cs   47  28  

我尝试仅从PCL库添加System.Threading.Tasks,这给出了7个不同的错误.我哪里错了?怎么做才能使这个工作?

请指导我这个.花了很多时间来最好地开发一个可以访问桌面应用和Win Phone应用程序的库.任何帮助都非常感激.谢谢.

1 个回答
  • 如果async在进行http调用时调用api,则还应该将该异步端点暴露给用户,而不是使用阻止请求Task.Wait.

    此外,在创建第三方库ConfigureAwait(false)时,建议在调用代码尝试访问Result属性或Wait方法时使用以避免死锁.您还应该遵循指南并使用任何异步方法标记Async,因此应该调用该方法ExecuteStatusAsync

    public static Task<bool> AgentStatusAsync() 
    {
        bool loginSuccess = false;
    
        try
        {
            // awaiting the task will unwrap it and return the JObject
            var jObject = await API_Utility.ExecuteGet("http://api.mintchat.com/agent/autoonline").ConfigureAwait(false);
    
        }
        catch
        {
        }
    }
    

    内部ExecuteGet:

    response = await client.SendAsync(reqMsg).ConfigureAwait(false);
    string content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
    

    如果IsSuccessStatusCode是false,您可以向调用代码抛出异常以显示出错的地方.要做到这一点,HttpResponseMessage.EnsureSuccessStatusCode如果状态代码!= 200 OK ,你可以使用它抛出异常.

    就个人而言,如果ExecuteGet是一个公共API方法,我绝对不会将其暴露为JObject强类型类型.

    2023-01-07 15:34 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有