Impostazione dei dati del corpo di una WebRequest


122

Sto creando una richiesta web in ASP.NET e ho bisogno di aggiungere una serie di dati al corpo. Come lo faccio?

var request = HttpWebRequest.Create(targetURL);
request.Method = "PUT";
response = (HttpWebResponse)request.GetResponse();

Risposte:


107

Con HttpWebRequest.GetRequestStream

Esempio di codice da 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);

Da uno dei miei codici:

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;
}

Ciao Torbjorn, sto usando la richiesta in modo da poter ottenere 'request.GetResponse ();', nell'esempio sopra come funzionerebbe?
William Calleja

Quando chiami GetRequestStream (), effettua la chiamata al server. Quindi, dovresti aggiungerlo alla fine dell'esempio sopra.
Torbjörn Hansson

1
C'è un modo per vedere il testo completo all'interno di un oggetto richiesta a scopo di debug? Ho provato a serializzarlo e ho provato a utilizzare uno StreamReader, ma non importa cosa faccio non riesco a vedere i dati che ho appena scritto nella richiesta.
James,

Fan-fottuta-tastic!

@ James, dovresti essere in grado di utilizzare fiddler o wirehark per vedere l'intera richiesta con il suo corpo.
RayLoveless

49

Aggiornare

Vedi la mia altra risposta SO.


Originale

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();

Ti manca qualcosa? Come un httpWReq.Content = newStream; non stai usando il tuo oggetto newStream con il tuo webRequest.
Yogurtu

4
Per rispondere alla domanda di completezza di @ Yogurtu, l' Streamoggetto che newStreampunta scrive direttamente nel corpo della richiesta. Vi si accede chiamando a HttpWReq.GetRequestStream(). Non è necessario impostare altro sulla richiesta.
MojoFilter

0

Le risposte in questo argomento sono tutte ottime. Comunque vorrei proporne un altro. Molto probabilmente ti è stata assegnata un'API e la desideri nel tuo progetto c #. Usando Postman, puoi configurare e testare la chiamata api lì e una volta eseguita correttamente, puoi semplicemente fare clic su "Codice" e la richiesta su cui hai lavorato viene scritta in ac # snippet. come questo:

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);

Il codice sopra dipende dal pacchetto nuget RestSharp, che puoi installare facilmente.

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.