我正在尝试使用简单的C#GUI应用程序调用我自己的REST API返回JSON,并且正在寻找最简单的方法:
http://danielmiessler.com:44821/token/dGVxdWllcm8=
我正在打开一个包含令牌的文件,并逐行读取内容以获取URL的最后部分:
StreamReader input = new StreamReader(openFileDialog1.OpenFile());
while ((line = input.ReadLine()) != null) {
这将回到文本框中:
textBox2.Text += ("\t" + result + "\r\n");
这是我试图重现的Ruby代码:
# Get our libraries
require 'httparty'
require 'json'
# Get our input from the command line
input = ARGV[0]
# Loop through the file
File.open("#{input}", "r").each_line do |line|
# Request the URL
response = HTTParty.get("http://danielmiessler.com:44821/token/#{line.chomp}")
# Go through the responses
case response.code
when 400
print "Improper input…\n"
# Feel free to remove this line if you want to reduce output.
when 200
json = JSON.parse(response.body)
print "Your input is #{json['type']} of the word: #{json['value']}\n"
when 404
print "There is no meaning in your token…\n"
# Feel free to remove this line if you want to reduce output.
end
end
如何根据文件中的标记进行调用并输出到文本框?
答案 0 :(得分:0)
您可以使用HttpClient
。
这是minimal example,可以帮助您入门:
static void Main(string[] args)
{
HttpClient client = new HttpClient();
client.GetAsync(_address).ContinueWith(
(requestTask) =>
{
HttpResponseMessage response = requestTask.Result;
response.EnsureSuccessStatusCode();
response.Content.ReadAsAsync<JsonArray>().ContinueWith(
(readTask) =>
{
Console.WriteLine(
"First 50 countries listed by The World Bank...");
foreach (var country in readTask.Result[1])
{
Console.WriteLine(" {0}, Country Code: {1}, " +
"Capital: {2}, Latitude: {3}, Longitude: {4}",
country.Value["name"],
country.Value["iso2Code"],
country.Value["capitalCity"],
country.Value["latitude"],
country.Value["longitude"]);
}
});
});
Console.WriteLine("Hit ENTER to exit...");
Console.ReadLine();
}