How to set the content of an HttpWebRequest in C#?

后端 未结 5 1700
余生分开走
余生分开走 2020-12-03 09:47

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

相关标签:
5条回答
  • 2020-12-03 10:09

    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);
    
    0 讨论(0)
  • 2020-12-03 10:13

    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();
    
    0 讨论(0)
  • 2020-12-03 10:15

    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.

    0 讨论(0)
  • 2020-12-03 10:22

    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();
    
    0 讨论(0)
  • 2020-12-03 10:25

    .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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题