Frage Wie man HTTP POST Web-Anfrage macht


Wie kann ich eine HTTP-Anfrage machen und einige Daten mit dem POST Methode? ich kann GET Anfrage, aber habe keine Ahnung, wie man ein macht POST.


739
2017-10-25 14:05


Ursprung


Antworten:


Es gibt mehrere Möglichkeiten, HTTP auszuführen GET und POST Anfragen:


Methode A: HttpClient

Verfügbar in: .NET Framework 4.5 und höher, .NET Standard 1.1 und höher, .NET Core 1.0 und höher

Derzeit der bevorzugte Ansatz. Asynchron. Portable Version für andere Plattformen verfügbar über NuGet.

using System.Net.Http;

Konfiguration

Es ist empfohlen einen instanziieren HttpClient für die Lebensdauer Ihrer Anwendung und teilen Sie sie.

private static readonly HttpClient client = new HttpClient();

POST

var values = new Dictionary<string, string>
{
   { "thing1", "hello" },
   { "thing2", "world" }
};

var content = new FormUrlEncodedContent(values);

var response = await client.PostAsync("http://www.example.com/recepticle.aspx", content);

var responseString = await response.Content.ReadAsStringAsync();

BEKOMMEN

var responseString = await client.GetStringAsync("http://www.example.com/recepticle.aspx");

Methode B: 3rd-Party Bibliotheken

Restschärfe

Bewährte Bibliothek für die Interaktion mit REST-APIs. Tragbar. Verfügbar über NuGet.

Flurl.Http

Neuere Bibliothek mit flüssiger API und Testhelfern. HttpClient unter der Haube. Tragbar. Verfügbar über NuGet.

using Flurl.Http;

POST

var responseString = await "http://www.example.com/recepticle.aspx"
    .PostUrlEncodedAsync(new { thing1 = "hello", thing2 = "world" })
    .ReceiveString();

BEKOMMEN

var responseString = await "http://www.example.com/recepticle.aspx"
    .GetStringAsync();

Methode C: Vermächtnis

Verfügbar in: .NET Framework 1.1, .NET Standard 2.0 und höher, .NET Core 1.0 und höher

using System.Net;
using System.Text;  // for class Encoding
using System.IO;    // for StreamReader

POST

var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");

var postData = "thing1=hello";
    postData += "&thing2=world";
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();

BEKOMMEN

var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");

var response = (HttpWebResponse)request.GetResponse();

var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

Methode D: WebClient (auch jetzt Legacy)

Verfügbar in: .NET Framework 1.1, .NET Standard 2.0 und höher, .NET Core 2.0 und höher

using System.Net;
using System.Collections.Specialized;

POST

using (var client = new WebClient())
{
    var values = new NameValueCollection();
    values["thing1"] = "hello";
    values["thing2"] = "world";

    var response = client.UploadValues("http://www.example.com/recepticle.aspx", values);

    var responseString = Encoding.Default.GetString(response);
}

BEKOMMEN

using (var client = new WebClient())
{
    var responseString = client.DownloadString("http://www.example.com/recepticle.aspx");
}

1501
2017-11-11 09:28



Einfache GET-Anfrage

using System.Net;

...

using (var wb = new WebClient())
{
    var response = wb.DownloadString(url);
}

Einfache POST-Anfrage

using System.Net;
using System.Collections.Specialized;

...

using (var wb = new WebClient())
{
    var data = new NameValueCollection();
    data["username"] = "myUser";
    data["password"] = "myPassword";

    var response = wb.UploadValues(url, "POST", data);
    string responseInString = Encoding.UTF8.GetString(response);
}

314
2017-10-25 14:07



MSDN hat eine Probe.

using System;
using System.IO;
using System.Net;
using System.Text;

namespace Examples.System.Net
{
    public class WebRequestPostExample
    {
        public static void Main()
        {
            // Create a request using a URL that can receive a post. 
            WebRequest request = WebRequest.Create("http://www.contoso.com/PostAccepter.aspx");
            // Set the Method property of the request to POST.
            request.Method = "POST";
            // Create POST data and convert it to a byte array.
            string postData = "This is a test that posts this string to a Web server.";
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            // Set the ContentType property of the WebRequest.
            request.ContentType = "application/x-www-form-urlencoded";
            // Set the ContentLength property of the WebRequest.
            request.ContentLength = byteArray.Length;
            // Get the request stream.
            Stream dataStream = request.GetRequestStream();
            // Write the data to the request stream.
            dataStream.Write(byteArray, 0, byteArray.Length);
            // Close the Stream object.
            dataStream.Close();
            // Get the response.
            WebResponse response = request.GetResponse();
            // Display the status.
            Console.WriteLine(((HttpWebResponse)response).StatusDescription);
            // Get the stream containing content returned by the server.
            dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            // Display the content.
            Console.WriteLine(responseFromServer);
            // Clean up the streams.
            reader.Close();
            dataStream.Close();
            response.Close();
        }
    }
}

51
2017-09-29 19:55



Dies ist ein vollständiges funktionierendes Beispiel für das Senden / Empfangen von Daten im JSON-Format. Ich habe VS2013 Express Edition verwendet

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;

namespace ConsoleApplication1
{
    class Customer
    {
        public string Name { get; set; }
        public string Address { get; set; }
        public string Phone { get; set; }
    }

    public class Program
    {
        private static readonly HttpClient _Client = new HttpClient();
        private static JavaScriptSerializer _Serializer = new JavaScriptSerializer();

        static void Main(string[] args)
        {
            Run().Wait();
        }

        static async Task Run()
        {
            string url = "http://www.example.com/api/Customer";
            Customer cust = new Customer() { Name = "Example Customer", Address = "Some example address", Phone = "Some phone number" };
            var json = _Serializer.Serialize(cust);
            var response = await Request(HttpMethod.Post, url, json, new Dictionary<string, string>());
            string responseText = await response.Content.ReadAsStringAsync();

            List<YourCustomClassModel> serializedResult = _Serializer.Deserialize<List<YourCustomClassModel>>(responseText);

            Console.WriteLine(responseText);
            Console.ReadLine();
        }

        /// <summary>
        /// Makes an async HTTP Request
        /// </summary>
        /// <param name="pMethod">Those methods you know: GET, POST, HEAD, etc...</param>
        /// <param name="pUrl">Very predictable...</param>
        /// <param name="pJsonContent">String data to POST on the server</param>
        /// <param name="pHeaders">If you use some kind of Authorization you should use this</param>
        /// <returns></returns>
        static async Task<HttpResponseMessage> Request(HttpMethod pMethod, string pUrl, string pJsonContent, Dictionary<string, string> pHeaders)
        {
            var httpRequestMessage = new HttpRequestMessage();
            httpRequestMessage.Method = pMethod;
            httpRequestMessage.RequestUri = new Uri(pUrl);
            foreach (var head in pHeaders)
            {
                httpRequestMessage.Headers.Add(head.Key, head.Value);
            }
            switch (pMethod.Method)
            {
                case "POST":
                    HttpContent httpContent = new StringContent(pJsonContent, Encoding.UTF8, "application/json");
                    httpRequestMessage.Content = httpContent;
                    break;

            }

            return await _Client.SendAsync(httpRequestMessage);
        }
    }
}

10
2017-10-25 14:07



Sie müssen das verwenden WebRequest Klasse und die GetRequestStream Methode.

Hier ist ein Beispiel.


7
2017-09-24 14:59



Einfache Lösung (Einzeiler, keine Fehlerüberprüfung, keine Wartezeiten) Lösung, die ich bisher gefunden habe

(new WebClient()).UploadStringAsync(new Uri(Address), dataString);‏

Verwenden Sie mit Vorsicht!


2
2018-02-20 21:28



Beim Benutzen Windows.Web.Http Namespace, für POST statt FormUrlEncodedContent schreiben wir HttpFormUrlEncodedContent. Die Antwort ist auch der Typ von HttpResponseMessage. Der Rest ist wie Evan Mulawski aufgeschrieben hat.


1
2018-04-16 11:33