SORU
3 Kasım 2010, ÇARŞAMBA


.NET: en Basit veri göndermek ve yanıt oku

Benim için sürpriz, bu, anladığım kadarıyla, bir şey kadar basit yapamam .NET META:

byte[] response = Http.Post
(
    url: "http://dork.com/service",
    contentType: "application/x-www-form-urlencoded",
    contentLength: 32,
    content: "home=Cosby&favorite flavor=flies"
);

Bu örnek kod, yukarıda bir HTTP POST veri ile yapar, ve 7* *statik bir sınıf Post bir yöntem yanıt verir.

Bu kolay bir şey olmadan terk ettiğimiz andan itibaren, bir sonraki en iyi çözüm nedir?

Nasıl veri ile bir HTTP POST gönderebilirim VE yanıt içeriğini almak?

CEVAP
3 Kasım 2010, ÇARŞAMBA


   using (WebClient client = new WebClient())
   {

       byte[] response =
       client.UploadValues("http://dork.com/service", new NameValueCollection()
       {
           { "home", "Cosby" },
           { "favorite flavor", "flies" }
       });

       string result = System.Text.Encoding.UTF8.GetString(response);
   }

İçerir: bunlara ihtiyacınız olacak

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

Sınıf/statik bir yöntem kullanma konusunda ısrarcı iseniz:

public static class Http
{
    public static byte[] Post(string uri, NameValueCollection pairs)
    {
        byte[] response = null;
        using (WebClient client = new WebClient())
        {
            response = client.UploadValues(uri, pairs);
        }
        return response;
    }
}

O zaman sadece:

var response = Http.Post("http://dork.com/service", new NameValueCollection() {
    { "home", "Cosby" },
    { "favorite flavor", "flies" }
});

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • ETrade Supply

    ETrade Suppl

    23 Temmuz 2011
  • How to Cook ?

    How to Cook

    31 Ocak 2007
  • WHZGUD2

    WHZGUD2

    21 EYLÜL 2011