【问题标题】:Calling My REST API Using C#使用 C# 调用我的 REST API
【发布时间】:2013-12-22 12:33:34
【问题描述】:

我正在尝试使用简单的 C# GUI 应用程序调用我自己的返回 JSON 的 REST API,并且正在寻找最简单的方法:

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

任何想法如何根据文件中的标记进行调用并输出到文本框?

【问题讨论】:

    标签: c# json api rest client


    【解决方案1】:

    您可以为此使用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(); 
    }
    

    【讨论】:

    • 我忘了说这是一个 GUI 应用程序,而不是控制台。我正在尝试将结果返回到我提到的 textbox2。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-26
    • 1970-01-01
    • 2018-05-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多