2

现在我一直在尝试Launchpad's API使用 C#.NET 或 Mono 来编写一个小的包装器。根据OAuth,我首先需要签署请求,并且Launchpad 有它自己的方式

我需要做的是使用一些必要的HTTP标头(例如Content-type. 在 python 中,我有 urllib2,但是当我浏览 System.Net 命名空间时,它让我大吃一惊。我无法理解如何开始。我是否可以使用WebRequest,HttpWebRequestWebClient. 使用 WebClient 我什至会收到证书错误,因为它们没有被添加为受信任的错误。

从 API Docs 中,它说三个密钥需要通过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);

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

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

4

1 回答 1

3

不,您需要在获取响应流之前关闭请求流。
像这样的东西:

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();
            }
        }
    }
}
于 2010-03-07T18:53:16.160 回答