首页 > 解决方案 > 从 API Post 返回字符串

问题描述

在 C# 中处理 API 调用非常新(通常是 C# 新手,这是第 3 天)。

我创建了下面的代码只是为了让我的脚湿透,但无论如何我无法弄清楚返回标记为“token”的字符串。

我需要在我的 Main 中使用它以供以后工作。我理解或相信我理解的事情:

任何帮助表示赞赏。

class Program {
  static void Main(string[] args) {
    string baseURL = "xxxxx";
    string UserName = "xxxx";
    string Password = "xxxxx";
    string api_key = "xxxxx";
    string api_token = "";
    GetToken(baseURL, UserName, Password, api_key);
  }
  async static string GetToken(string url, string username, string password, string apikey) {
    using (HttpClient client = new HttpClient()) {
      TokenRequestor tokenRequest = new TokenRequestor(apikey, username, password);
      string JSONresult = JsonConvert.SerializeObject(tokenRequest);
      HttpContent c = new StringContent(JSONresult, Encoding.UTF8, "application/json");
      HttpResponseMessage message = await client.PostAsync(url, c);
      string tokenJSON = await message.Content.ReadAsStringAsync();
      string pattern = "token\":\"([a-z0-9]*)";
      Regex myRegex = new Regex(pattern, RegexOptions.IgnoreCase);
      Match m = myRegex.Match(tokenJSON);
      String string_m = m.ToString();
      char[] chars = { ':' };
      string[] matches = string_m.Split(chars);
      string final_match = matches[1].Trim(new Char[] { '"' });
      string token = final_match;
    }
  }
}
public class TokenRequestor {
  public string method;
  public string module;
  public string key;
  public RequestMaker request;
  public TokenRequestor(string apikey, string Name, string pwd) {
    method = "get";
    module = "api.login";
    key = apikey;
    request = new RequestMaker(Name, pwd);
  }
}
public class RequestMaker {
  public string username;
  public string password;
  public RequestMaker(string uname, string pwd) {
    username = uname;
    password = pwd;
  }
}

标签: c#

解决方案


GetToken()将方法的返回类型从 更改voidTask<string>token然后你可以从返回字符串GetToken()

此外,您的Main方法签名需要更改为,static async Task Main(string[] args)以便您可以GetToken()按如下方式调用等待对象:

string token = await GetToken(baseURL, UserName, Password, api_key);从你的Main

using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

public class Program
{
        static async Task Main(string[] args)
        {
            string baseURL = "xxxxx";
            string UserName = "xxxx";
            string Password = "xxxxx";
            string api_key = "xxxxx";
            string api_token = "";

            string token = await GetToken(baseURL, UserName, Password, api_key);
        }

        static async Task<string> GetToken(string url, string username, string password, string apikey)
        {
            string token = string.Empty;

            using (HttpClient client = new HttpClient())
            {
                TokenRequestor tokenRequest = new TokenRequestor(apikey, username, password);
                string JSONresult = JsonConvert.SerializeObject(tokenRequest);
                HttpContent c = new StringContent(JSONresult, Encoding.UTF8, "application/json");
                HttpResponseMessage message = await client.PostAsync(url, c);    
                string tokenJSON = await message.Content.ReadAsStringAsync();   
                string pattern = "token\":\"([a-z0-9]*)";
                Regex myRegex = new Regex(pattern, RegexOptions.IgnoreCase);
                Match m = myRegex.Match(tokenJSON);
                String string_m = m.ToString();
                char[] chars = { ':' };
                string[] matches = string_m.Split(chars);
                string final_match = matches[1].Trim(new Char[] { '"' });
                token = final_match;
            }

            return token;
        }            
}

public class TokenRequestor
{

    public string method;
    public string module;
    public string key;
    public RequestMaker request;

    public TokenRequestor(string apikey, string Name, string pwd)
    {
        method = "get";
        module = "api.login";
        key = apikey;
        request = new RequestMaker(Name, pwd);
    }


}

public class RequestMaker
{
    public string username;
    public string password;

    public RequestMaker(string uname, string pwd)
    {
        username = uname;
        password = pwd;

    }        
}

推荐阅读