简体   繁体   中英

Calling My REST API Using C#

I'm trying to call my own REST API that returns JSON using a simple C# GUI application, and am looking for the simplest way to do so:

http://danielmiessler.com:44821/token/dGVxdWllcm8=

I am opening a file containing tokens and reading the contents line by line to get the final part of the URL:

StreamReader input = new StreamReader(openFileDialog1.OpenFile());

while ((line = input.ReadLine()) != null) {

This is going back into a textbox:

textBox2.Text += ("\t" + result + "\r\n");

Here is the Ruby code I'm trying to reproduce:

# 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

Any ideas how to make the calls based on the tokens in the file and output to the text box?

You can use HttpClient for that.

This is a minimal example to get you started:

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

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