de-vraag
  • Pytania
  • Tagi
  • Użytkownicy
Powiadomienia
Nagrody
Rejestracja
Po zarejestrowaniu się, będziesz otrzymywać powiadomienia o odpowiedziach i komentarzach do swoich pytań.
Zaloguj się
Brak tłumaczeń pasujących do Twojego wyszukiwania Jeśli masz już konto, zaloguj się, aby sprawdzić nowe powiadomienia.
Za dodane pytania, odpowiedzi i komentarze przewidziane są nagrody.
Więcej
Źródło
Edytuj
 Hooch
Hooch
Question

Jak wykonać żądanie HTTP POST

Kanoniczne
Jak mogę wykonać żądanie HTTP i wysłać jakieś dane używając metody POST **?

Potrafię wykonać żądanie GET, ale nie mam pojęcia jak zrobić POST.

1020 2010-10-25T14:05:58+00:00 3
Nicolás  Alarcón Rapela
Nicolás Alarcón Rapela
Edytowane pytanie 2. września 2019 в 1:55
Programowanie
.net
c#
httprequest
post
httpwebrequest
To pytanie ma 1 odpowiedź w języku angielskim, aby je przeczytać zaloguj się na swoje konto.
Solution / Answer
Evan Mulawski
Evan Mulawski
25. października 2010 в 2:08
2010-10-25T14:08:07+00:00
Więcej
Źródło
Edytuj
#11235113

Istnieje kilka sposobów na wykonanie żądań HTTP GET i POST:


Metoda A: HttpClient (preferowana)

To jest wrapper wokół HttpWebRequest. Porównaj z WebClient.

Dostępne w: .NET Framework 4.5+, .NET Standard 1.1+, .NET Core 1.0+ .

Obecnie preferowane podejście. Asynchroniczne. Wersja przenośna dla innych platform dostępna przez NuGet.

using System.Net.Http;

Konfiguracja

Jest zalecane, aby utworzyć jeden HttpClient na cały czas działania aplikacji i udostępnić go.

private static readonly HttpClient client = new HttpClient();

Zobacz HttpClientFactory dla rozwiązania Dependency Injection.


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

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

Metoda B: Biblioteki stron trzecich

  • RestSharp

Sprawdzona i przetestowana biblioteka do interakcji z interfejsami API REST. Przenośna. Dostępna przez NuGet.

  • Flurl.Http

Nowsza biblioteka z płynnym API i pomocnikami do testowania. HttpClient pod maską. Przenośna. Dostępna przez NuGet.

    using Flurl.Http;

  • POST

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

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

Metoda C: HttpWebRequest (Nie zalecana dla nowych prac)

Dostępne w: .NET Framework 1.1+, .NET Standard 2.0+, .NET Core 1.0+.

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=" + Uri.EscapeDataString("hello");
          postData += "&thing2=" + Uri.EscapeDataString("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();
  • GET

      var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");
    
      var response = (HttpWebResponse)request.GetResponse();
    
      var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

Metoda D: WebClient (Nie zalecane dla nowych prac)

To jest wrapper wokół HttpWebRequest. Porównaj z HttpClient.

Dostępny w: .NET Framework 1.1+, NET Standard 2.0+, .NET Core 2.0+.

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);
      }
  • GET

      using (var client = new WebClient())
      {
          var responseString = client.DownloadString("http://www.example.com/recepticle.aspx");
      }
Nicol&#225;s  Alarc&#243;n Rapela
Nicolás Alarcón Rapela
Edytowana odpowiedź 1. września 2019 в 6:08
Use IHttpClientFactory to implement resilient HTTP requests | Microsoft Docs
Learn how to use IHttpClientFactory, available since .NET Core 2.1, for creating `HttpClient` instances, making it easy for you to use it in your applications.
docs.microsoft.com
Improper Instantiation antipattern - Azure Architecture Center | Microsoft Docs
Avoid continually creating new instances of an object that is meant to be created once and then shared.
docs.microsoft.com
GitHub - restsharp/RestSharp: Simple REST and HTTP API Client for .NET
Simple REST and HTTP API Client for .NET. Contribute to restsharp/RestSharp development by creating an account on GitHub.
github.com
Flurl
Fluent URL building and wrist-friendly HTTP client for .NET
flurl.dev
1984
0
Pavlo Neyman
Pavlo Neyman
11. listopada 2011 в 9:28
2011-11-11T09:28:26+00:00
Więcej
Źródło
Edytuj
#11235116

Proste żądanie GET

using System.Net;

...

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

Proste żądanie POST

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);
}
J. Doe
J. Doe
Edytowana odpowiedź 6. stycznia 2018 в 9:55
360
0
Ot&#225;vio D&#233;cio
Otávio Décio
25. października 2010 в 2:07
2010-10-25T14:07:31+00:00
Więcej
Źródło
Edytuj
#11235112

MSDN ma próbkę.

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();
        }
    }
}
 Endorphinex
Endorphinex
Edytowana odpowiedź 31. lipca 2017 в 4:31
61
0
Dodaj pytanie
Kategorie
Wszystkie
Technologia
Kultura / Rekreacja
Życie / Sztuka
Nauka
Profesjonalny
Biznes
Użytkownicy
Wszystkie
Nowy
Popularny
1
Jasur Fozilov
Zarejestrowany 10 godzin temu
2
Zuxriddin Muydinov
Zarejestrowany 1 dzień temu
3
Денис Анненский
Zarejestrowany 3 dni temu
4
365
Zarejestrowany 1 tydzień temu
5
True Image
Zarejestrowany 1 tydzień temu
BG
DA
DE
EL
ES
FR
ID
IT
JA
LT
LV
NL
PL
PT
RO
RU
SK
TR
ZH
© de-vraag 2022
Źródło
stackoverflow.com
na podstawie licencji cc by-sa 3.0 z przypisaniem