【发布时间】:2014-11-24 15:27:43
【问题描述】:
我还是 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 上查看的示例,但不知道为什么我会收到这条消息“�”。
我是这种算法的新手,如果有人可以分享一本书或教程来说明如何做这种事情(解释每个步骤),我将不胜感激
【问题讨论】:
-
见zetcode.com/csharp/httpclient非常简单清晰的例子
标签: c# .net httpwebrequest