如何在 C# 中设置 HttpWebRequest 的内容?

发布于 2024-10-28 18:28:04 字数 71 浏览 1 评论 0原文

HttpWebRequest 具有 ContentLength 和 ContentType 属性,但是如何实际设置请求的内容呢?

An HttpWebRequest has the properties ContentLength and ContentType, but how do you actually set the content of the request?

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

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

发布评论

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

评论(5

随遇而安 2024-11-04 18:28:04

以下内容应该可以帮助您入门

byte[]  buffer = ...request data as bytes
var webReq = (HttpWebRequest) WebRequest.Create("http://127.0.0.1/target");

webReq.Method = "REQUIRED METHOD";
webReq.ContentType = "REQUIRED CONTENT TYPE";
webReq.ContentLength = buffer.Length;

var reqStream = webReq.GetRequestStream();
reqStream.Write(buffer, 0, buffer.Length);
reqStream.Close();

var webResp = (HttpWebResponse) webReq.GetResponse();

The following should get you started

byte[]  buffer = ...request data as bytes
var webReq = (HttpWebRequest) WebRequest.Create("http://127.0.0.1/target");

webReq.Method = "REQUIRED METHOD";
webReq.ContentType = "REQUIRED CONTENT TYPE";
webReq.ContentLength = buffer.Length;

var reqStream = webReq.GetRequestStream();
reqStream.Write(buffer, 0, buffer.Length);
reqStream.Close();

var webResp = (HttpWebResponse) webReq.GetResponse();
过期情话 2024-11-04 18:28:04

.NET 4.5(或通过添加来自 NuGet 的 Microsoft.Net.Http 包的 .NET 4.0)提供了很多设置请求内容的额外灵活性。这是一个例子:

private System.IO.Stream Upload(string actionUrl, string paramString, Stream paramFileStream, byte [] paramFileBytes)
{
    HttpContent stringContent = new StringContent(paramString);
    HttpContent fileStreamContent = new StreamContent(paramFileStream);
    HttpContent bytesContent = new ByteArrayContent(paramFileBytes);
    using (var client = new HttpClient())
    using (var formData = new MultipartFormDataContent())
    {
        formData.Add(stringContent, "param1", "param1");
        formData.Add(fileStreamContent, "file1", "file1");
        formData.Add(bytesContent, "file2", "file2");
        var response = client.PostAsync(actionUrl, formData).Result;
        if (!response.IsSuccessStatusCode)
        {
            return null;
        }
        return response.Content.ReadAsStreamAsync().Result;
    }
}

.NET 4.5 (or .NET 4.0 by adding the Microsoft.Net.Http package from NuGet) provides a lot of additional flexibility in setting the request content. Here is an example:

private System.IO.Stream Upload(string actionUrl, string paramString, Stream paramFileStream, byte [] paramFileBytes)
{
    HttpContent stringContent = new StringContent(paramString);
    HttpContent fileStreamContent = new StreamContent(paramFileStream);
    HttpContent bytesContent = new ByteArrayContent(paramFileBytes);
    using (var client = new HttpClient())
    using (var formData = new MultipartFormDataContent())
    {
        formData.Add(stringContent, "param1", "param1");
        formData.Add(fileStreamContent, "file1", "file1");
        formData.Add(bytesContent, "file2", "file2");
        var response = client.PostAsync(actionUrl, formData).Result;
        if (!response.IsSuccessStatusCode)
        {
            return null;
        }
        return response.Content.ReadAsStreamAsync().Result;
    }
}
纵山崖 2024-11-04 18:28:04

这是一个不同的选项,用于发布信息而不干扰字节和流。我个人认为它更容易理解、阅读和调试。

// Convert Object to JSON
var requestMessage = JsonConvert.SerializeObject(requestObject);
var content = new StringContent(requestMessage, Encoding.UTF8, "application/json");

// Create the Client
var client = new HttpClient();
client.DefaultRequestHeaders.Add(AuthKey, AuthValue);

// Post the JSON
var responseMessage = client.PostAsync(requestEndPoint, content).Result;
var stringResult = responseMessage.Content.ReadAsStringAsync().Result;

// Convert JSON back to the Object
var responseObject = JsonConvert.DeserializeObject<ResponseObject>(stringResult);

Here's a different option for posting info without messing with Bytes and Streams. I personally find it easier to follow, read, and debug.

// Convert Object to JSON
var requestMessage = JsonConvert.SerializeObject(requestObject);
var content = new StringContent(requestMessage, Encoding.UTF8, "application/json");

// Create the Client
var client = new HttpClient();
client.DefaultRequestHeaders.Add(AuthKey, AuthValue);

// Post the JSON
var responseMessage = client.PostAsync(requestEndPoint, content).Result;
var stringResult = responseMessage.Content.ReadAsStringAsync().Result;

// Convert JSON back to the Object
var responseObject = JsonConvert.DeserializeObject<ResponseObject>(stringResult);
不可一世的女人 2024-11-04 18:28:04

HttpWebRequest 的 RequestStream 是操作所在 - 粗略代码...

//build the request object
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(http://someapi.com/);
//write the input data (aka post) to a byte array
byte[] requestBytes = new ASCIIEncoding().GetBytes(inputData);
//get the request stream to write the post to
Stream requestStream = request.GetRequestStream();
//write the post to the request stream
requestStream.Write(requestBytes, 0, requestBytes.Length);

如果您要发送扩展字符,请使用 UTF8Encoding,请确保您也设置了正确的内容类型/字符集标头。

HttpWebRequest's RequestStream is where the action is at - rough code...

//build the request object
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(http://someapi.com/);
//write the input data (aka post) to a byte array
byte[] requestBytes = new ASCIIEncoding().GetBytes(inputData);
//get the request stream to write the post to
Stream requestStream = request.GetRequestStream();
//write the post to the request stream
requestStream.Write(requestBytes, 0, requestBytes.Length);

If you're sending extended chars, use UTF8Encoding, make sure you set the right content-type/charset header too.

往事随风而去 2024-11-04 18:28:04

HttpWebRequest.GetRequestStream() 获取请求流。设置标头后,使用 GetRequestStream() 并将内容写入流。

这篇文章解释了如何使用HttpWebRequest传输文件,它应该提供如何发送内容的一个很好的示例。

但是,基本上格式是

 var stream = request.GetRequestStream();
 stream.Write( stuff );
 stream.Close();
 var response = request.GetResponse();

HttpWebRequest.GetRequestStream() gets the request Stream. After you have set the headers, use GetRequestStream() and write the content to the stream.

This post explains how to transmit files using HttpWebRequest, which should provide a good example of how to send content.

But, basically the format would be

 var stream = request.GetRequestStream();
 stream.Write( stuff );
 stream.Close();
 var response = request.GetResponse();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文