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

后端 未结 5 1712
余生分开走
余生分开走 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: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.

提交回复
热议问题