如何在 C#.NET/Mono 中使用 HTTP 库来使用请求-响应

发布于 2024-08-24 08:41:19 字数 1924 浏览 7 评论 0原文

现在我一直在尝试使用 Launchpad 的 API 使用 C#.NET 或 Mono 编写一个小型包装器。 根据 OAuth,我首先需要对请求进行签名,并且 Launchpad 有自己的这样做的方式

我需要做的是创建到 https://edge.launchpad.net/+request 的连接-token 以及一些必要的 HTTP 标头,例如 Content-type。在 python 中,我有 urllib2,但是当我浏览 System.Net 命名空间时,它让我大吃一惊。我不明白如何开始。我是否可以使用 WebRequestHttpWebRequest 还是 WebClient 有很多困惑。使用 WebClient,我什至收到证书错误,因为它们没有添加为受信任的证书。

从API文档来看,它说需要通过POST发送三个密钥

  • auth_consumer_key:您的消费者密钥
  • oauth_signature_method:字符串“PLAINTEXT”
  • oauth_signature:字符串“&”。

因此,HTTP 请求可能如下所示:

POST /+request-token HTTP/1.1
Host: edge.launchpad.net
Content-type: application/x-www-form-urlencoded

oauth_consumer_key=just+testing&oauth_signature_method=PLAINTEXT&oauth_signature=%26

响应应如下所示:

200 OK

oauth_token=9kDgVhXlcVn52HGgCWxq&oauth_token_secret=jMth55Zn3pbkPGNht450XHNcHVGTJm9Cqf5ww5HlfxfhEEPKFflMqCXHNVWnj2sWgdPjqDJNRDFlt92f

我多次更改了代码,最后我所能得到的内容类似于“

HttpWebRequest clnt = HttpWebRequest.Create(baseAddress) as HttpWebRequest;
// Set the content type
clnt.ContentType =  "application/x-www-form-urlencoded";
clnt.Method = "POST";

string[] listOfData ={
    "oauth_consumer_key="+oauth_consumer_key, 
    "oauth_signature="+oauth_signature, 
    "oauth_signature_method"+oauth_signature_method
};

string postData = string.Join("&",listOfData);
byte[] dataBytes= Encoding.ASCII.GetBytes(postData);

Stream newStream = clnt.GetRequestStream();
newStream.Write(dataBytes,0,dataBytes.Length);

如何进一步进行?”我应该对 clnt 进行 Read 调用吗?

为什么 .NET 开发人员不能创建一个我们可以用来读写的类,而不是创建数百个类并让每个新手感到困惑。

Right now I have been trying to use Launchpad's API to write a small wrapper over it using C#.NET or Mono.
As per OAuth, I first need to get the requests signed and Launchpad has it's own way of doing so.

What I need to do is to create a connection to https://edge.launchpad.net/+request-token with some necessary HTTP Headers like Content-type. In python I have urllib2, but as I glanced in System.Net namespace, it blew off my head. I was not able to understand how to start off with it. There is a lot of confusion whether I can use WebRequest, HttpWebRequest or WebClient. With WebClient I even get Certificate errors since, they are not added as trusted ones.

From the API Docs, it says that three keys need to sent via POST

  • auth_consumer_key: Your consumer key
  • oauth_signature_method: The string "PLAINTEXT"
  • oauth_signature: The string "&".

So the HTTP request might look like this:

POST /+request-token HTTP/1.1
Host: edge.launchpad.net
Content-type: application/x-www-form-urlencoded

oauth_consumer_key=just+testing&oauth_signature_method=PLAINTEXT&oauth_signature=%26

The response should look something like this:

200 OK

oauth_token=9kDgVhXlcVn52HGgCWxq&oauth_token_secret=jMth55Zn3pbkPGNht450XHNcHVGTJm9Cqf5ww5HlfxfhEEPKFflMqCXHNVWnj2sWgdPjqDJNRDFlt92f

I changed my code many times and finally all I can get it something like

HttpWebRequest clnt = HttpWebRequest.Create(baseAddress) as HttpWebRequest;
// Set the content type
clnt.ContentType =  "application/x-www-form-urlencoded";
clnt.Method = "POST";

string[] listOfData ={
    "oauth_consumer_key="+oauth_consumer_key, 
    "oauth_signature="+oauth_signature, 
    "oauth_signature_method"+oauth_signature_method
};

string postData = string.Join("&",listOfData);
byte[] dataBytes= Encoding.ASCII.GetBytes(postData);

Stream newStream = clnt.GetRequestStream();
newStream.Write(dataBytes,0,dataBytes.Length);

How do I proceed further? Should I do a Read call on clnt ?

Why can't .NET devs make one class which we can use to read and write instead of creating hundreds of classes and confusing every newcomer.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夜声 2024-08-31 08:41:19

不可以,您需要在获取响应流之前关闭请求流。
像这样的事情:

Stream s= null;
try
{
    s = clnt.GetRequestStream();
    s.Write(dataBytes, 0, dataBytes.Length);
    s.Close();

    // get the response
    try
    {
        HttpWebResponse resp = (HttpWebResponse) req.GetResponse();
        if (resp == null) return null;

        // expected response is a 200 
        if ((int)(resp.StatusCode) != 200)
            throw new Exception(String.Format("unexpected status code ({0})", resp.StatusCode));
        for(int i=0; i < resp.Headers.Count; ++i)  
                ;  //whatever

        var MyStreamReader = new System.IO.StreamReader(resp.GetResponseStream());
        string fullResponse = MyStreamReader.ReadToEnd().Trim();
    }
    catch (Exception ex1)
    {
        // handle 404, 503, etc...here
    }
}    
catch 
{
}

但是如果您不需要所有控制,您可以更简单地执行 WebClient 请求。

string address = "https://edge.launchpad.net/+request-token";
string data = "oauth_consumer_key=just+testing&oauth_signature_method=....";
string reply = null;
using (WebClient client = new WebClient ())
{
  client.Headers.Add("Content-Type","application/x-www-form-urlencoded");
  reply = client.UploadString (address, data);
}

完整的工作代码(在.NET v3.5中编译):

using System;
using System.Net;
using System.Collections.Generic;
using System.Reflection;

// to allow fast ngen
[assembly: AssemblyTitle("launchpad.cs")]
[assembly: AssemblyDescription("insert purpose here")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Dino Chiesa")]
[assembly: AssemblyProduct("Tools")]
[assembly: AssemblyCopyright("Copyright © Dino Chiesa 2010")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.1.1.1")]

namespace Cheeso.ToolsAndTests
{
    public class launchpad
    {
        public void Run()
        {
            // see http://tinyurl.com/yfkhwkq
            string address = "https://edge.launchpad.net/+request-token";

            string oauth_consumer_key = "stackoverflow1";
            string oauth_signature_method = "PLAINTEXT";
            string oauth_signature = "%26";

            string[] listOfData ={
                "oauth_consumer_key="+oauth_consumer_key,
                "oauth_signature_method="+oauth_signature_method,
                "oauth_signature="+oauth_signature
            };

            string data = String.Join("&",listOfData);

            string reply = null;
            using (WebClient client = new WebClient ())
            {
                client.Headers.Add("Content-Type","application/x-www-form-urlencoded");
                reply = client.UploadString (address, data);
            }

            System.Console.WriteLine("response: {0}", reply);
        }

        public static void Usage()
        {
            Console.WriteLine("\nlaunchpad: request token from launchpad.net\n");
            Console.WriteLine("Usage:\n  launchpad");
        }


        public static void Main(string[] args)
        {
            try
            {
                new launchpad()
                    .Run();
            }
            catch (System.Exception exc1)
            {
                Console.WriteLine("Exception: {0}", exc1.ToString());
                Usage();
            }
        }
    }
}

No, you need to close the request stream before getting the response stream.
Something like this:

Stream s= null;
try
{
    s = clnt.GetRequestStream();
    s.Write(dataBytes, 0, dataBytes.Length);
    s.Close();

    // get the response
    try
    {
        HttpWebResponse resp = (HttpWebResponse) req.GetResponse();
        if (resp == null) return null;

        // expected response is a 200 
        if ((int)(resp.StatusCode) != 200)
            throw new Exception(String.Format("unexpected status code ({0})", resp.StatusCode));
        for(int i=0; i < resp.Headers.Count; ++i)  
                ;  //whatever

        var MyStreamReader = new System.IO.StreamReader(resp.GetResponseStream());
        string fullResponse = MyStreamReader.ReadToEnd().Trim();
    }
    catch (Exception ex1)
    {
        // handle 404, 503, etc...here
    }
}    
catch 
{
}

But if you don't need all the control, you can do a WebClient request more simply.

string address = "https://edge.launchpad.net/+request-token";
string data = "oauth_consumer_key=just+testing&oauth_signature_method=....";
string reply = null;
using (WebClient client = new WebClient ())
{
  client.Headers.Add("Content-Type","application/x-www-form-urlencoded");
  reply = client.UploadString (address, data);
}

Full working code (compile in .NET v3.5):

using System;
using System.Net;
using System.Collections.Generic;
using System.Reflection;

// to allow fast ngen
[assembly: AssemblyTitle("launchpad.cs")]
[assembly: AssemblyDescription("insert purpose here")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Dino Chiesa")]
[assembly: AssemblyProduct("Tools")]
[assembly: AssemblyCopyright("Copyright © Dino Chiesa 2010")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.1.1.1")]

namespace Cheeso.ToolsAndTests
{
    public class launchpad
    {
        public void Run()
        {
            // see http://tinyurl.com/yfkhwkq
            string address = "https://edge.launchpad.net/+request-token";

            string oauth_consumer_key = "stackoverflow1";
            string oauth_signature_method = "PLAINTEXT";
            string oauth_signature = "%26";

            string[] listOfData ={
                "oauth_consumer_key="+oauth_consumer_key,
                "oauth_signature_method="+oauth_signature_method,
                "oauth_signature="+oauth_signature
            };

            string data = String.Join("&",listOfData);

            string reply = null;
            using (WebClient client = new WebClient ())
            {
                client.Headers.Add("Content-Type","application/x-www-form-urlencoded");
                reply = client.UploadString (address, data);
            }

            System.Console.WriteLine("response: {0}", reply);
        }

        public static void Usage()
        {
            Console.WriteLine("\nlaunchpad: request token from launchpad.net\n");
            Console.WriteLine("Usage:\n  launchpad");
        }


        public static void Main(string[] args)
        {
            try
            {
                new launchpad()
                    .Run();
            }
            catch (System.Exception exc1)
            {
                Console.WriteLine("Exception: {0}", exc1.ToString());
                Usage();
            }
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文