使用C#中的API调用非常陌生(一般来说,这是C#的第三天)。
我创建了下面的代码,只是弄湿了我的脚,但无论如何我都无法弄清楚是否返回标有“ token”的字符串。
在以后的工作中,我需要在Main中使用它。我了解或相信我了解的事情:
GetToken
由于void
而无法返回值。GetToken
方法仅是string
或返回void
,因此无法将async
更改为void
而不是Task
。任何帮助表示赞赏。
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;
}
}
答案 0 :(得分:2)
将GetToken()
方法的返回类型从void
更改为Task<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;
}
}
答案 1 :(得分:0)
async static string GetToken(string url, string username, string password, string apikey)
应该是
async static Task<String> GetToken(...)
返回异步任务中的值(“方法”)
答案 2 :(得分:0)
NGambits的答案很好,尽管在这种情况下,我能够完全放弃异步并使用message.Content.ReadAsStringAsync()。Result来返回我需要的值。
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;
}
}