Estou criando uma solicitação da Web no ASP.NET e preciso adicionar um monte de dados ao corpo. Como faço isso?
var request = HttpWebRequest.Create(targetURL);
request.Method = "PUT";
response = (HttpWebResponse)request.GetResponse();
Estou criando uma solicitação da Web no ASP.NET e preciso adicionar um monte de dados ao corpo. Como faço isso?
var request = HttpWebRequest.Create(targetURL);
request.Method = "PUT";
response = (HttpWebResponse)request.GetResponse();
Respostas:
Com HttpWebRequest.GetRequestStream
Exemplo de código de 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);
De um de meu próprio código:
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;
}
Atualizar
Original
var request = (HttpWebRequest)WebRequest.Create("https://example.com/endpoint");
string stringData = ""; // place body here
var data = Encoding.Default.GetBytes(stringData); // note: choose appropriate encoding
request.Method = "PUT";
request.ContentType = ""; // place MIME type here
request.ContentLength = data.Length;
var newStream = request.GetRequestStream(); // get a ref to the request body so it can be modified
newStream.Write(data, 0, data.Length);
newStream.Close();
Streamobjeto que newStreamaponta é escrito diretamente no corpo da solicitação. Ele é acessado pela chamada para HttpWReq.GetRequestStream(). Não há necessidade de definir mais nada na solicitação.
As respostas neste tópico são excelentes. No entanto, gostaria de propor outro. Provavelmente, você recebeu uma API e quer isso em seu projeto c #. Usando o Postman, você pode configurar e testar a chamada de api lá e, uma vez que ela seja executada corretamente, você pode simplesmente clicar em 'Código' e a solicitação na qual você está trabalhando é gravada em um snippet c #. como isso:
var client = new RestClient("https://api.XXXXX.nl/oauth/token");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Basic N2I1YTM4************************************jI0YzJhNDg=");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("grant_type", "password");
request.AddParameter("username", "development+XXXXXXXX-admin@XXXXXXX.XXXX");
request.AddParameter("password", "XXXXXXXXXXXXX");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
O código acima depende do pacote nuget RestSharp, que você pode instalar facilmente.