设置 WebRequest 的请求体数据

142

我在ASP.NET中创建一个网络请求,需要向主体添加大量数据。我该怎么做?

var request = HttpWebRequest.Create(targetURL);
request.Method = "PUT";
response = (HttpWebResponse)request.GetResponse();
3个回答

120

使用 HttpWebRequest.GetRequestStream 方法

来自 http://msdn.microsoft.com/en-us/library/d4cek6cc.aspx 的代码示例

string postData = "firstone=" + inputData;
ASCIIEncoding encoding = new ASCIIEncoding ();
byte[] byte1 = encoding.GetBytes (postData);

// Set the content type of the data being posted.
myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";

// Set the content length of the string being posted.
myHttpWebRequest.ContentLength = byte1.Length;

Stream newStream = myHttpWebRequest.GetRequestStream ();

newStream.Write (byte1, 0, byte1.Length);

以下是我的代码之一:

var request = (HttpWebRequest)WebRequest.Create(uri);
request.Credentials = this.credentials;
request.Method = method;
request.ContentType = "application/atom+xml;type=entry";
using (Stream requestStream = request.GetRequestStream())
using (var xmlWriter = XmlWriter.Create(requestStream, new XmlWriterSettings() { Indent = true, NewLineHandling = NewLineHandling.Entitize, }))
{
    cmisAtomEntry.WriteXml(xmlWriter);
}

try 
{    
    return (HttpWebResponse)request.GetResponse();  
}
catch (WebException wex)
{
    var httpResponse = wex.Response as HttpWebResponse;
    if (httpResponse != null)
    {
        throw new ApplicationException(string.Format(
            "Remote server call {0} {1} resulted in a http error {2} {3}.",
            method,
            uri,
            httpResponse.StatusCode,
            httpResponse.StatusDescription), wex);
    }
    else
    {
        throw new ApplicationException(string.Format(
            "Remote server call {0} {1} resulted in an error.",
            method,
            uri), wex);
    }
}
catch (Exception)
{
    throw;
}

嗨Torbjorn,我正在使用请求(request)来获取'request.GetResponse();',在上面的例子中它是如何工作的? - William Calleja
1
当您调用GetRequestStream()时,它会向服务器发出请求。因此,您需要将其添加到上面示例的末尾。 - Torbjörn Hansson
1
有没有一种方法可以查看请求对象内的完整文本以进行调试?我尝试过序列化它并尝试使用StreamReader,但无论我做什么,都无法看到我刚刚写入请求的数据。 - James
太棒了! - user235273
@James,你应该能够使用Fiddler或Wireshark查看完整的请求及其正文。 - RayLoveless

52

更新

请查看我的其他SO回答。


原始内容

var request = (HttpWebRequest)WebRequest.Create("https://example.com/endpoint");

string stringData = ""; // place body here
var data = Encoding.Default.GetBytes(stringData); // note: choose appropriate encoding

request.Method = "PUT";
request.ContentType = ""; // place MIME type here
request.ContentLength = data.Length;

var newStream = request.GetRequestStream(); // get a ref to the request body so it can be modified
newStream.Write(data, 0, data.Length);
newStream.Close();

你有什么遗漏的吗?比如 httpWReq.Content = newStream; 你没有将 newStream 对象与 webRequest 一起使用。 - Yogurtu
4
为了完整回答@Yogurtu的问题,newStream指向的Stream对象直接写入请求的主体。它通过调用HttpWReq.GetRequestStream()进行访问。在请求中不需要设置任何其他内容。 - MojoFilter

9
这个主题中的答案都很好。但我想提出另外一个解决方案。很可能您已经获得了一个API,并希望将其添加到您的C#项目中。使用Postman,您可以在那里设置和测试API调用,一旦它成功运行,您只需单击“代码”,您正在使用的请求就会被写入一个C#片段,如下所示:
var client = new RestClient("https://api.XXXXX.nl/oauth/token");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Basic   N2I1YTM4************************************jI0YzJhNDg=");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("grant_type", "password");
request.AddParameter("username", "development+XXXXXXXX-admin@XXXXXXX.XXXX");
request.AddParameter("password", "XXXXXXXXXXXXX");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

上述代码依赖于NuGet软件包RestSharp,您可以轻松安装。

一个补充:在Postman窗口的右上方,您可以找到“代码”按钮,用于设置和测试API调用。 - real_yggdrasil
天啊,我不知道这个存在!太棒了! - LarryBud

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接