Setting a WebRequest's body data
With HttpWebRequest.GetRequestStream
Code example from 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);
From one of my own code:
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;
}
How to pass header and Body value using HttpWebRequest in C#?
Here is correct HttpWebRequest
using:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(pathapi);
request.Method = "POST";
string postData = "grant_type=client_credentials&client_id=ruban123&client_secret=123456";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] bytes = encoding.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = bytes.Length;
Stream newStream = request.GetRequestStream();
newStream.Write(bytes, 0, bytes.Length);
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
HttpWebRequest approach is not relevant. Look at this question Setting Authorization Header of HttpClient
How can I Post data using HttpWebRequest?
You can do by this
var request = HttpWebRequest.Create("http://example.com/api/Phrase/GetJDTO");
var postData = "Jlpt = 2";
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
but I suggest you use HttpClient
rather than HttpWebRequest
in this case
Adding a json body to a POST with WebRequest
Solved it by just swapping to a simple async call.
public async Task<IEnumerable<Inventory>> CreateSale(IpPartial ipPartial, Inventory[] inventories)
{
string jsonString = new JavaScriptSerializer().Serialize(inventories);
var data = new StringContent(jsonString, Encoding.UTF8, "application/json");
var url = "http://localhost:5002/api/Sale/CreateSales";
using var client = new HttpClient();
var response = await client.PostAsync(url, data);
string result = response.Content.ReadAsStringAsync().Result;
return inventories;
}
how to set up request body with httpWebRequest
You create the HttpWebRequest
object, get the request stream, and write your parameters to it. The example at HttpRequest.GetRequestStream should point you in the right direction.
Related Topics
Async/Await - Is It *Concurrent*
Trim Last Character from a String
Different Ways of Adding to Dictionary
Get All Properties Which Marked Certain Attribute
How to Know the Selected Checkboxes from Within the Httppost Create Action Method
Dynamically Switch Wcf Web Service Reference Url Path Through Config File
Setting Culture for ASP.NET MVC Application on VS Dev Server and Iis
How to Make Form1 Label.Text Change When Checkbox on Form2 Is Checked
Convert String to System.Io.Stream
Read a Xml (From a String) and Get Some Fields - Problems Reading Xml
Dynamic Button Creation & Placing Them in a Predefined Order Using C#
Finding Property Differences Between Two C# Objects
What Are the Differences Between the Xmlserializer and Binaryformatter