简体   繁体   中英

Return String From API Post

Very new to working with API calls in C# (new to C# in general, this is day 3).

I created the below code to just give my feet wet, but I cannot figure out anyway to return the string labeled "token".

I'll need to use this in my Main for later work. Things I understand or believe I understand:

  • GetToken cannot return a value due to void .
  • Changing GetToken to string rather than void does not work due to async methods only being void or returning Task .

Any help appreciated.

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;
  }
}

Change return type of GetToken() method from void to Task<string> . Then you can return the string token from GetToken()

Also, your Main method signature needs to change to static async Task Main(string[] args) so that you can call the awaitable GetToken() as follows :

string token = await GetToken(baseURL, UserName, Password, api_key); from your 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;

    }        
}

async static string GetToken(string url, string username, string password, string apikey)

should be

async static Task<String> GetToken(...)

to return values in an async Task ("method")

NGambits answer was great, although in this case I was able to ditch async entirely and use message.Content.ReadAsStringAsync().Result to be able to return the value I needed.

  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");

            //Console.WriteLine(JSONresult);

            HttpResponseMessage message =  client.PostAsync(url, c).Result;
            // Console.WriteLine(await message.Content.ReadAsStringAsync());
            string tokenJSON =  message.Content.ReadAsStringAsync().Result;

            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;

            Console.WriteLine(token); //just for testing purposes to make sure i'm getting the data I want. 

            return token;

        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM