如何在 C#.NET/Mono 中使用 HTTP 库来使用请求-响应
-
25-09-2019 - |
题
现在我一直在尝试使用 Launchpad's API
使用 C#.NET 或 Mono 编写一个小包装器。按照 OAuth
, ,我首先需要签署请求并 Launchpad 有它自己的方法.
我需要做的是创建一个连接 https://edge.launchpad.net/+request-token 一些必要的 HTTP 标头,例如 Content-type
. 。在 python 中,我有 urllib2,但是当我浏览 System.Net 命名空间时,它让我大吃一惊。我不明白如何开始。是否可以使用有很多困惑 WebRequest
, HttpWebRequest
或者 WebClient
. 。使用 WebClient,我什至收到证书错误,因为它们没有添加为受信任的证书。
从 API 文档来看,它说需要通过以下方式发送三个密钥 POST
- auth_consumer_key:您的消费钥匙
- oauth_signature_method:字符串“PLAINTEXT”
- oauth_签名:字符串“&”。
所以 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 开发人员不能创建一个我们可以用来读写的类,而不是创建数百个类并让每个新手感到困惑。
解决方案
不,您需要在获取响应流之前关闭请求流。
像这样的东西:
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();
}
}
}
}
不隶属于 StackOverflow