简体   繁体   English

ASP.NET-GET Web请求API

[英]ASP.NET - GET Web Request API

I'm new to APIs, so I've been trying to use a web request to GET information from Reddit, since the API is unlocked. 我是API的新手,由于API已解锁,因此我一直在尝试使用Web请求从Reddit获取信息。 I've been able to use the right URL to get information using a REST client extension, but I want to implement the body of the data and simply just print it out to a web page. 我已经能够使用正确的URL通过REST客户端扩展来获取信息,但是我想实现数据主体,只是将其打印到网页上即可。

I know this is easier with python, but they use C#/ASP.NET at my work. 我知道使用python会更容易,但是他们在我的工作中使用C#/ ASP.NET。 I've looked off of tutorials such as: 我看过以下教程:

http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client

I was only able to obtain a header when I used this tutorial and my code is: 使用本教程时,我只能获取标头,而我的代码是:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace API_TESTING
{
    class Product
    {
        public string Name { get; set; }
        public double Price { get; set; }
    }
    class Program
    {
    static void Main()
    {
        RunAsync().Wait();
    }

    static async Task RunAsync()
    {
        using(var client = new HttpClient())
        {
            //TODO - send HTTP requests
            client.BaseAddress = new Uri("http://www.reddit.com/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            //-----
            HttpResponseMessage response =  await client.GetAsync("r/todayilearned/new.json");
            if(response.IsSuccessStatusCode)
            {
                Console.Write(response);

            }

        }
    }
}
}

Can someone explain how to use ASP.NET for API calls? 有人可以解释如何使用ASP.NET进行API调用吗? or link to other up-to-date tutorials? 或链接到其他最新教程? Thank you. 谢谢。

You're almost there. 你快到了。 After you get the response, you need to read its content. 得到响应后,您需要阅读其内容。

var response = await _client.GetAsync(uri);
if (response.IsSuccessStatusCode) {
    var result = await response.Content.ReadAsStringAsync();
    Console.WriteLine(result);
}

You might want to check out the RedditSharp project to see how others have done this. 您可能想查看RedditSharp项目,以了解其他人如何做到这一点。 Btw, the tutorial you linked to does almost exactly what I answered with under the Getting a Resource (HTTP GET) section. 顺便说一句,您链接到的教程几乎与我在“获取资源(HTTP GET)”部分中回答的内容完全一样。 Only difference is they used the generic ReadAsAsync while you can use ReadAsStringAsync if you're just writing the body to the console. 唯一的不同是,它们使用通用的ReadAsAsync而如果您只是将主体写入控制台,则可以使用ReadAsStringAsync

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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