简体   繁体   中英

How do I send a POST request with a body that is a string or a character using httpwebrequest?

I have a Post call that takes a string GUID "AA0DB615-D4CB-4466-BC23-0E0083002220" I am using HTTPWebRequest to send request but I am not sure how to add this along with my Post request. Basically I have not found any method inside the HTTPWebRequest to send a Post that is just a string or a character datatype. Is their anything like request.AddBody.

I have also looked at the GetResponseStream. Can I use this to write to the body as a string or character data type and send the call. I am stuck on this any help would be great

Here's a sample request that sends a plain text GUID in the body using HttpWebRequest , You can set the Content type to "text/plain" if you want to explicitly state that the content type is plain text:

var request = (HttpWebRequest)WebRequest.Create("URL GOES HERE");
request.Method = "POST";
var content = Guid.NewGuid().ToString(); //You should replace this with your GUID
var encoding = new ASCIIEncoding();
var bytes = encoding.GetBytes(content);
request.ContentType = "text/plain";
request.ContentLength = bytes.Length;
using (var requestStream = request.GetRequestStream())
{
    requestStream.Write(bytes, 0, bytes.Length);
    var response = request.GetResponse() as HttpWebResponse;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM