C#如何正确发出http Web GET请求

我仍然对C#还是陌生的,并且我正在尝试为此页面创建一个应用程序,当我收到通知(回答,评论等)时,它将告诉我。但是现在,我只是尝试对api进行简单的调用,以获取用户的数据。

我正在使用Visual Studio Express

2012构建C#应用程序,现在(在此情况下)您输入用户ID,因此该应用程序将使用用户ID进行请求并显示此用户ID的统计信息。

这是我试图发出请求的代码:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

//Request library

using System.Net;

using System.IO;

namespace TestApplication

{

class Connect

{

public string id;

public string type;

protected string api = "https://api.stackexchange.com/2.2/";

protected string options = "?order=desc&sort=name&site=stackoverflow";

public string request()

{

string totalUrl = this.join(id);

return this.HttpGet(totalUrl);

}

protected string join(string s)

{

return api + type + "/" + s + options;

}

protected string get(string url)

{

try

{

string rt;

WebRequest request = WebRequest.Create(url);

WebResponse response = request.GetResponse();

Stream dataStream = response.GetResponseStream();

StreamReader reader = new StreamReader(dataStream);

rt = reader.ReadToEnd();

Console.WriteLine(rt);

reader.Close();

response.Close();

return rt;

}

catch(Exception ex)

{

return "Error: " + ex.Message;

}

}

public string HttpGet(string URI)

{

WebClient client = new WebClient();

// Add a user agent header in case the

// requested URI contains a query.

client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");

Stream data = client.OpenRead(URI);

StreamReader reader = new StreamReader(data);

string s = reader.ReadToEnd();

data.Close();

reader.Close();

return s;

}

}

}

该类是一个对象,只需解析用户ID并发出请求即可从表单中访问它。

我已经尝试了许多在google上查看过的示例,但不知道为什么我会一直使用此消息。

我是这种算法的新手,如果任何人都可以共享一本书或教程来展示如何做这种事情(解释每个步骤),我将不胜感激

回答:

服务器有时会压缩其响应以节省带宽,当这种情况发生时,您需要在尝试读取响应之前对其进行解压缩。幸运的是,.NET框架可以自动执行此操作,但是,我们必须打开该设置。

这是如何实现此目的的示例。

string html = string.Empty;

string url = @"https://api.stackexchange.com/2.2/answers?order=desc&sort=activity&site=stackoverflow";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

request.AutomaticDecompression = DecompressionMethods.GZip;

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())

using (Stream stream = response.GetResponseStream())

using (StreamReader reader = new StreamReader(stream))

{

html = reader.ReadToEnd();

}

Console.WriteLine(html);


编辑 17/11/23

更新以抛出使用GET请求和POST异步的示例


public string Get(string uri)

{

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);

request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

using(HttpWebResponse response = (HttpWebResponse)request.GetResponse())

using(Stream stream = response.GetResponseStream())

using(StreamReader reader = new StreamReader(stream))

{

return reader.ReadToEnd();

}

}


public async Task<string> GetAsync(string uri)

{

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);

request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

using(HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())

using(Stream stream = response.GetResponseStream())

using(StreamReader reader = new StreamReader(stream))

{

return await reader.ReadToEndAsync();

}

}


在您希望使用其他HTTP方法(例如PUT,DELETE和ETC)时

包含参数method

public string Post(string uri, string data, string contentType, string method = "POST")

{

byte[] dataBytes = Encoding.UTF8.GetBytes(data);

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);

request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

request.ContentLength = dataBytes.Length;

request.ContentType = contentType;

request.Method = method;

using(Stream requestBody = request.GetRequestStream())

{

requestBody.Write(dataBytes, 0, dataBytes.Length);

}

using(HttpWebResponse response = (HttpWebResponse)request.GetResponse())

using(Stream stream = response.GetResponseStream())

using(StreamReader reader = new StreamReader(stream))

{

return reader.ReadToEnd();

}

}


在您希望使用其他HTTP方法(例如PUT,DELETE和ETC)时

包含参数method

public async Task<string> PostAsync(string uri, string data, string contentType, string method = "POST")

{

byte[] dataBytes = Encoding.UTF8.GetBytes(data);

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);

request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

request.ContentLength = dataBytes.Length;

request.ContentType = contentType;

request.Method = method;

using(Stream requestBody = request.GetRequestStream())

{

await requestBody.WriteAsync(dataBytes, 0, dataBytes.Length);

}

using(HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())

using(Stream stream = response.GetResponseStream())

using(StreamReader reader = new StreamReader(stream))

{

return await reader.ReadToEndAsync();

}

}

以上是 C#如何正确发出http Web GET请求 的全部内容, 来源链接: utcz.com/qa/436136.html

回到顶部