从以下给定的POST数据中创建HttpWebRequest

时间:2013-08-22 12:16:25

标签: c# twitter system.net.httpwebrequest

谈到网络开发,我知之甚少......

我从以下网站找到了一些代码和解释。 https://dev.twitter.com/docs/auth/implementing-sign-twitter

最终,我想用twitter实现登录。但我无法将这些POST Web请求重写为c#HttpWebRequest格式,我可以在其余的应用程序中重复使用。如果我们检查第一次网络请求......

POST /oauth/request_token HTTP/1.1
 User-Agent: themattharris' HTTP Client
 Host: api.twitter.com
 Accept: */*
 Authorization: 
    OAuth oauth_callback="http%3A%2F%2Flocalhost%2Fsign-in-with-twitter%2F",
          oauth_consumer_key="cChZNFj6T5R0TigYB9yd1w",
          oauth_nonce="ea9ec8429b68d6b77cd5600adbbb0456",
          oauth_signature="F1Li3tvehgcraF8DMJ7OyxO4w9Y%3D",
          oauth_signature_method="HMAC-SHA1",
          oauth_timestamp="1318467427",
          oauth_version="1.0"

我想将其转换为有效的HttpWebRequest。 迄今。我的代码看起来像这样......

HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create("https://api.twitter.com/oauth/request_token");

        ASCIIEncoding encoding = new ASCIIEncoding();

        httpReq.Method = "POST";
        httpReq.ContentType = "application/x-www-form-urlencoded";
        httpReq.Accept = "Accept=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";

不幸的是,我的确走了多远...我不知道这些请求是如何运作的。我需要包含其余数据并拨打电话。但我被卡住了。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

试试这个:

ASCIIEncoding encoder = new ASCIIEncoding();
byte[] data = encoder.GetBytes(serializedObject); // the data you wanted to send

HttpWebRequest request = new WebRequest.Create("https://api.twitter.com/oauth/request_token") as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;

request.GetRequestCode().Write(data, 0, data.Length);

也是一个可能的dublicate(类似的问题):Why I get 411 Length required error?