HTTP POST वेब अनुरोध कैसे करें


1132

Canonical
मैं एक HTTP अनुरोध कैसे बना सकता हूं और विधि का उपयोग करके कुछ डेटा भेज सकता हूं POST ?

मैं एक GETअनुरोध कर सकता हूं , लेकिन मुझे यह पता नहीं है कि POSTअनुरोध कैसे करना है ।

जवाबों:


2163

HTTP GETऔर POSTअनुरोध करने के कई तरीके हैं:


विधि A: HttpClient (पसंदीदा)

में उपलब्ध है: .NET Framework 4.5+, .NET Standard 1.1+, .NET Core 1.0+

यह वर्तमान में पसंदीदा दृष्टिकोण है, और अतुल्यकालिक और उच्च प्रदर्शन है। अधिकांश मामलों में अंतर्निहित संस्करण का उपयोग करें, लेकिन बहुत पुराने प्लेटफार्मों के लिए एक NuGet पैकेज है

using System.Net.Http;

सेट अप

यहHttpClient आपके आवेदन के जीवनकाल के लिए एक को तत्काल करने और इसे साझा करने की सिफारिश की जाती है जब तक कि आपके पास कोई विशिष्ट कारण न हो।

private static readonly HttpClient client = new HttpClient();

HttpClientFactoryएक निर्भरता इंजेक्शन समाधान के लिए देखें ।


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

विधि बी: तृतीय-पक्ष पुस्तकालय

RestSharp

  • POST

     var client = new RestClient("http://example.com");
     // client.Authenticator = new HttpBasicAuthenticator(username, password);
     var request = new RestRequest("resource/{id}");
     request.AddParameter("thing1", "Hello");
     request.AddParameter("thing2", "world");
     request.AddHeader("header", "value");
     request.AddFile("file", path);
     var response = client.Post(request);
     var content = response.Content; // Raw content as string
     var response2 = client.Post<Person>(request);
     var name = response2.Data.Name;
    

Flurl.Http

यह एक नया पुस्तकालय है जो धाराप्रवाह एपीआई, परीक्षण सहायकों को स्पोर्ट करता है, हुड के नीचे HttpClient का उपयोग करता है, और पोर्टेबल है। यह 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();
    

विधि C: HttpWebRequest (नए कार्य के लिए अनुशंसित नहीं)

में उपलब्ध है: .NET Framework 1.1+, .NET Standard 2.0+, .NET Core 1.0+। .NET कोर में, यह ज्यादातर संगतता के लिए है - यह लपेटता है HttpClient, कम प्रदर्शन करने वाला है, और नई सुविधाएँ नहीं मिलेगी।

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

विधि D: WebClient (नए कार्य के लिए अनुशंसित नहीं)

यह चारों ओर एक आवरण है HttpWebRequestसे तुलना करेंHttpClient

में उपलब्ध है: .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");
    }
    

2
@ लॉयड:HttpWebResponse response = (HttpWebResponse)HttpWReq.GetResponse();
इवान मुलवस्की

2
आप ASCII का उपयोग क्यों करते हैं? अगर किसी को UTF-8 के साथ xml की आवश्यकता हो तो क्या होगा?
जीरो

8
मैं एक मरे हुए घोड़े को मारने से नफरत करता हूं, लेकिन आपको करना चाहिएresponse.Result.Content.ReadAsStringAsync()
डेविड एस।

13
आपने क्यों कहा कि WebRequest और WebClient विरासत हैं? MSDN यह नहीं कहता कि वे पदावनत हैं या कुछ भी। क्या मैं कुछ भूल रहा हूँ?
हाईप

23
@ हाई: वे पदावनत नहीं हैं, वेब अनुरोध करने के नए (और ज्यादातर मामलों, बेहतर और अधिक लचीले) तरीके हैं। मेरी राय में, सरल, गैर-महत्वपूर्ण कार्यों के लिए, पुराने तरीके ठीक हैं - लेकिन यह आपके ऊपर है और जो भी आप सबसे अधिक आरामदायक हैं।
इवान मुलवस्की

384

सरल GET अनुरोध

using System.Net;

...

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

सरल पोस्ट अनुरोध

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

15
+1 नियमित सामान POST के लिए कोड का इतना छोटा टुकड़ा होना बहुत अच्छा है।
user_v

3
टिम - यदि आप राइट-क्लिक करें जो कि शाब्दिक रूप से हल नहीं किया जा सकता है, तो आपको एक रिज़ॉल्यूशन संदर्भ मेनू मिलेगा, जिसमें आपके लिए यूजिंग स्टेटमेंट को जोड़ने के लिए क्रियाएं शामिल हैं। यदि रिज़ॉल्यूशन संदर्भ मेनू दिखाई नहीं देता है, तो इसका मतलब है कि आपको पहले संदर्भ जोड़ने की आवश्यकता है।
कैमरन विल्बी

मैंने आपके उत्तर को अच्छा माना क्योंकि यह बहुत सरल और स्पष्ट है।
हूच

13
मैं जोड़ना चाहूंगा कि POST अनुरोध के लिए प्रतिक्रिया चर एक बाइट सरणी है। स्ट्रिंग प्रतिक्रिया प्राप्त करने के लिए आप बस Encoding.ASCII.GetString (प्रतिक्रिया) करें; (सिस्टम.पाठ का प्रयोग करके)
Sindre

1
इसके अलावा, आप थोड़ा जटिल सरणी $ _POST ['उपयोगकर्ता'] भेज सकते हैं: डेटा ["उपयोगकर्ता [उपयोगकर्ता नाम]"] = "myUsername"; डेटा ["उपयोगकर्ता [पासवर्ड]"] = "myPassword";
बिमल पौडेल

68

MSDN का एक नमूना है।

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

किसी कारण से यह काम नहीं किया जब मैं बड़ी मात्रा में डेटा भेज रहा था
AnKing

26

यह JSON प्रारूप में डेटा भेजने / प्राप्त करने का एक पूर्ण कार्य उदाहरण है, मैंने विज़ुअल स्टूडियो 2013 एक्सप्रेस संस्करण का उपयोग किया है :

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

8

यहाँ पर कुछ अच्छे जवाब हैं। मुझे WebClient () के साथ अपने हेडर सेट करने के लिए एक अलग तरीका पोस्ट करने दें। मैं आपको एपीआई कुंजी सेट करने का तरीका भी दिखाऊंगा।

        var client = new WebClient();
        string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(userName + ":" + passWord));
        client.Headers[HttpRequestHeader.Authorization] = $"Basic {credentials}";
        //If you have your data stored in an object serialize it into json to pass to the webclient with Newtonsoft's JsonConvert
        var encodedJson = JsonConvert.SerializeObject(newAccount);

        client.Headers.Add($"x-api-key:{ApiKey}");
        client.Headers.Add("Content-Type:application/json");
        try
        {
            var response = client.UploadString($"{apiurl}", encodedJson);
            //if you have a model to deserialize the json into Newtonsoft will help bind the data to the model, this is an extremely useful trick for GET calls when you have a lot of data, you can strongly type a model and dump it into an instance of that class.
            Response response1 = JsonConvert.DeserializeObject<Response>(response);

उपयोगी, धन्यवाद। BTW ऐसा लगता है कि हेडर-प्रॉपर्टीज़ सेट करने के लिए उपरोक्त तकनीक पुराने (पदावनत?), HttpWebRequest दृष्टिकोण के लिए भी काम करती है। जैसे myReq.Headers [HttpRequestHeader.Authorization] = $ "मूल {साख}};
Zeek2

6

यह समाधान कुछ भी नहीं बल्कि मानक .NET कॉल का उपयोग करता है।

परीक्षण:

  • एक उद्यम WPF आवेदन में उपयोग में। यूआई को अवरुद्ध करने से बचने के लिए async / प्रतीक्षा का उपयोग करता है।
  • .NET 4.5+ के साथ संगत।
  • बिना मापदंडों के परीक्षण किया जाता है (पर्दे के पीछे "GET" की आवश्यकता होती है)।
  • मापदंडों के साथ परीक्षण किया गया (पर्दे के पीछे "पोस्ट" की आवश्यकता है)।
  • Google जैसे एक मानक वेब पेज के साथ परीक्षण किया गया।
  • एक आंतरिक जावा-आधारित वेब सेवा के साथ परीक्षण किया गया।

संदर्भ:

// Add a Reference to the assembly System.Web

कोड:

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;

private async Task<WebResponse> CallUri(string url, TimeSpan timeout)
{
    var uri = new Uri(url);
    NameValueCollection rawParameters = HttpUtility.ParseQueryString(uri.Query);
    var parameters = new Dictionary<string, string>();
    foreach (string p in rawParameters.Keys)
    {
        parameters[p] = rawParameters[p];
    }

    var client = new HttpClient { Timeout = timeout };
    HttpResponseMessage response;
    if (parameters.Count == 0)
    {
        response = await client.GetAsync(url);
    }
    else
    {
        var content = new FormUrlEncodedContent(parameters);
        string urlMinusParameters = uri.OriginalString.Split('?')[0]; // Parameters always follow the '?' symbol.
        response = await client.PostAsync(urlMinusParameters, content);
    }
    var responseString = await response.Content.ReadAsStringAsync();

    return new WebResponse(response.StatusCode, responseString);
}

private class WebResponse
{
    public WebResponse(HttpStatusCode httpStatusCode, string response)
    {
        this.HttpStatusCode = httpStatusCode;
        this.Response = response;
    }
    public HttpStatusCode HttpStatusCode { get; }
    public string Response { get; }
}

बिना मापदंडों के कॉल करने के लिए (पर्दे के पीछे "GET" का उपयोग करता है):

 var timeout = TimeSpan.FromSeconds(300);
 WebResponse response = await this.CallUri("http://www.google.com/", timeout);
 if (response.HttpStatusCode == HttpStatusCode.OK)
 {
     Console.Write(response.Response); // Print HTML.
 }

मापदंडों के साथ कॉल करने के लिए (पर्दे के पीछे "पोस्ट" का उपयोग करता है):

 var timeout = TimeSpan.FromSeconds(300);
 WebResponse response = await this.CallUri("http://example.com/path/to/page?name=ferret&color=purple", timeout);
 if (response.HttpStatusCode == HttpStatusCode.OK)
 {
     Console.Write(response.Response); // Print HTML.
 }

6

सरल (एक-लाइनर, कोई त्रुटि जाँच नहीं, प्रतिक्रिया की प्रतीक्षा नहीं) समाधान मैंने अब तक पाया है:

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

सावधानी से प्रयोग करें!


5
जो कि काफी खराब है। मैं इसकी सिफारिश नहीं करता हूं क्योंकि किसी भी तरह की कोई त्रुटि नहीं है और यह डिबगिंग दर्द है। इसके अतिरिक्त पहले से ही इस सवाल का बहुत अच्छा जवाब है।
हूच

1
@ दूसरों को इस प्रकार के उत्तरों में दिलचस्पी हो सकती है, भले ही यह सबसे अच्छा नहीं हो।
मीतुल बत्ती

सहमत, एकमात्र संदर्भ जिसमें यह उपयोगी होगा, कोड गोल्फिंग है और सी # में गोल्फ कौन है?)
एक्सग्रेगोरी

4

जब हम FormUrlEncodedContent के बजाय POST के लिए Windows.Web.Http नाम स्थान का उपयोग करते हैं , तो हम HttpFormUrlEncodedContent लिखते हैं। इसके अलावा प्रतिक्रिया HttpResponseMessage का प्रकार है। बाकी जैसा कि इवान मुलवस्की ने लिखा है।


4

यदि आप एक धाराप्रवाह एपीआई पसंद करते हैं, तो आप टिनी .estClient का उपयोग कर सकते हैं । यह NuGet पर उपलब्ध है ।

var client = new TinyRestClient(new HttpClient(), "http://MyAPI.com/api");
// POST
var city = new City() { Name = "Paris", Country = "France" };
// With content
var response = await client.PostRequest("City", city)
                           .ExecuteAsync<bool>();

1

यह पूरी तरह से तुच्छ क्यों नहीं है? अनुरोध करना और विशेष रूप से परिणामों से निपटना नहीं है और ऐसा लगता है कि कुछ .NET बग भी शामिल हैं - बग को देखें HttpClient.GetAsync में WebException को फेंकना चाहिए, न कि TaskCanceledException को।

मैं इस कोड के साथ समाप्त हुआ:

static async Task<(bool Success, WebExceptionStatus WebExceptionStatus, HttpStatusCode? HttpStatusCode, string ResponseAsString)> HttpRequestAsync(HttpClient httpClient, string url, string postBuffer = null, CancellationTokenSource cts = null) {
    try {
        HttpResponseMessage resp = null;

        if (postBuffer is null) {
            resp = cts is null ? await httpClient.GetAsync(url) : await httpClient.GetAsync(url, cts.Token);

        } else {
            using (var httpContent = new StringContent(postBuffer)) {
                resp = cts is null ? await httpClient.PostAsync(url, httpContent) : await httpClient.PostAsync(url, httpContent, cts.Token);
            }
        }

        var respString = await resp.Content.ReadAsStringAsync();
        return (resp.IsSuccessStatusCode, WebExceptionStatus.Success, resp.StatusCode, respString);

    } catch (WebException ex) {
        WebExceptionStatus status = ex.Status;
        if (status == WebExceptionStatus.ProtocolError) {
            // Get HttpWebResponse so that you can check the HTTP status code.
            using (HttpWebResponse httpResponse = (HttpWebResponse)ex.Response) {
                return (false, status, httpResponse.StatusCode, httpResponse.StatusDescription);
            }
        } else {
            return (false, status, null, ex.ToString()); 
        }

    } catch (TaskCanceledException ex) {
        if (cts is object && ex.CancellationToken == cts.Token) {
            // a real cancellation, triggered by the caller
            return (false, WebExceptionStatus.RequestCanceled, null, ex.ToString());
        } else {
            // a web request timeout (possibly other things!?)
            return (false, WebExceptionStatus.Timeout, null, ex.ToString());
        }

    } catch (Exception ex) {
        return (false, WebExceptionStatus.UnknownError, null, ex.ToString());
    }
}

यह एक GET करेगा या POST निर्भर करता है कि postBufferक्या अशक्त है या नहीं

अगर सफलता सच है तो प्रतिक्रिया अंदर होगी ResponseAsString

यदि सफलता झूठी है, तो आप जांच कर सकते हैं WebExceptionStatus, HttpStatusCodeऔर ResponseAsStringयह देखने की कोशिश कर सकते हैं कि क्या गलत हुआ।


0

इननेट कोर में आप निम्नलिखित कोड के साथ पोस्ट-कॉल कर सकते हैं, यहां मैंने इस कोड में कुछ अतिरिक्त विशेषताएं जोड़ी हैं ताकि आपके कोड को प्रॉक्सी के पीछे और नेटवर्क क्रेडेंशियल्स के साथ यदि कोई हो, तो यहां भी मैं उल्लेख कर सकता हूं कि आप एन्कोडिंग को बदल सकते हैं आपका सन्देश। मुझे उम्मीद है कि यह सब समझाता है और कोडिंग में आपकी मदद करता है।

HttpClient client = GetHttpClient(_config);

        if (headers != null)
        {
            foreach (var header in headers)
            {
                client.DefaultRequestHeaders.TryAddWithoutValidation(header.Key, header.Value);
            }
        }

        client.BaseAddress = new Uri(baseAddress);

        Encoding encoding = Encoding.UTF8;


        var result = await client.PostAsync(url, new StringContent(body, encoding, "application/json")).ConfigureAwait(false);
        if (result.IsSuccessStatusCode)
        {
            return new RequestResponse { severity = "Success", httpResponse = result.Content.ReadAsStringAsync().Result, StatusCode = result.StatusCode };
        }
        else
        {
            return new RequestResponse { severity = "failure", httpResponse = result.Content.ReadAsStringAsync().Result, StatusCode = result.StatusCode };
        }


 public HttpClient GetHttpClient(IConfiguration _config)
        {
            bool ProxyEnable = Convert.ToBoolean(_config["GlobalSettings:ProxyEnable"]);

            HttpClient client = null;
            if (!ProxyEnable)
            {
                client = new HttpClient();
            }
            else
            {
                string ProxyURL = _config["GlobalSettings:ProxyURL"];
                string ProxyUserName = _config["GlobalSettings:ProxyUserName"];
                string ProxyPassword = _config["GlobalSettings:ProxyPassword"];
                string[] ExceptionURL = _config["GlobalSettings:ExceptionURL"].Split(';');
                bool BypassProxyOnLocal = Convert.ToBoolean(_config["GlobalSettings:BypassProxyOnLocal"]);
                bool UseDefaultCredentials = Convert.ToBoolean(_config["GlobalSettings:UseDefaultCredentials"]);

                WebProxy proxy = new WebProxy
                {
                    Address = new Uri(ProxyURL),
                    BypassProxyOnLocal = BypassProxyOnLocal,
                    UseDefaultCredentials = UseDefaultCredentials,
                    BypassList = ExceptionURL,
                    Credentials = new NetworkCredential(ProxyUserName, ProxyPassword)

                };

                HttpClientHandler handler = new HttpClientHandler { Proxy = proxy };
                client = new HttpClient(handler,true);
            }
            return client;
        }
हमारी साइट का प्रयोग करके, आप स्वीकार करते हैं कि आपने हमारी Cookie Policy और निजता नीति को पढ़ और समझा लिया है।
Licensed under cc by-sa 3.0 with attribution required.