4

I'm very new to C# and want to learn how to make HTTP requests. I want to start really simple, although that is currently evading me. I want to just perform a GET on, say, google.com. I created a command line application, and have this code. Not sure at all which usings are required.

I tested it by writing to the console, and it doesn't get past the response. Can somebody please clue me in? I'm looking to do some simple curl type stuff to test an existing API. Thank you for your help.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;

namespace APItest
{
    class testClass
    {
        static void Main(string[] args)
        {
            string url = "http://www.google.com";

            Console.WriteLine(url);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            Console.ReadKey();
        }
    }
}
4

4 回答 4

4

我会考虑使用HttpClient来代替,它是为了在 .net 4 中更容易调用 rest API 而创建的。它还支持asyncawait.

你可以这样称呼它(使用异步):

async Task<HttpResponseMessage> GetGoogle() {

    HttpClient client = new HttpClient();

    Uri uri = new Uri("http://www.google.com");

    var result = await client.GetAsync(uri);

    return result;
}
于 2013-09-30T02:24:04.583 回答
2

我不建议使用 HTTPWebRequest/HTTPWebResponse 在 .Net 中使用 Web 服务。 RestSharp更容易使用。

于 2013-09-30T01:58:14.613 回答
1

您正在寻找的是WebClient课程。它有一套丰富的方法来完成大多数与 HTTP 相关的任务,链接到下面的完整文档

网络客户端 MSDN

于 2013-09-30T02:58:30.477 回答
0

您需要阅读回复:

var stream = response.GetResponseStream();

然后你有你的流并用它做你需要的事情。 GetResponseStream

于 2013-09-30T02:04:48.153 回答