Unconfigured Ad Widget

Collapse

Anúncio

Collapse
No announcement yet.

Como fazer uma requisição do tipo POST

Collapse
X
 
  • Filter
  • Tempo
  • Show
Clear All
new posts

  • Font Size
    #1

    C# Como fazer uma requisição do tipo POST

    Segue o exemplo todo comentado, é só copiar e se precisar, fazer alguns ajustes para adequar às suas necessidades.

    Testado e funcionando com .NET 2.0
    Código PHP:
    using System;
    using System.Net;
    using System.IO;
    using System.Text;
    using System.  Web// não esqueça de fazer referência a dll em seu projeto

    namespace  Microsoft.Samples.QuickStart.HowTo.Net.WebRequests
    {
        static class 
    ClientPOST
        
    {
            public static 
    void Main(string[] args)
            {
                
    // Enviando para a página do terra os parametros pelo método post
                
    GetPage("http://www.guiadohacker.com.br""parametro1=valor1&parametro2=valor2");

                
    Console.WriteLine();
                
    Console.WriteLine("Pressione algo para continuar...");
                
    Console.ReadLine();
            }

            private static 
    void GetPage(String urlString query)
            {
                
    // Declarações necessárias
                
    Stream requestStream null;
                
    WebResponse response null;
                
    StreamReader reader null;

                try
                {
                    
    WebRequest request WebRequest.Create(url);
                    
    request.Method WebRequestMethods.Http.Post;

                    
    // Neste ponto, você está setando a propriedade ContentType da página 
                    // para urlencoded para que o comando POST seja enviado corretamente
                    
    request.ContentType "application/x-www-form-urlencoded";

                    
    StringBuilder urlEncoded = new StringBuilder();

                    
    // Separando cada parâmetro
                    
    Char[] reserved = { '?''=''&' };

                    
    // alocando o bytebuffer
                    
    byte[] byteBuffer null;

                    
    // caso a URL seja preenchida
                    
    if (query != null)
                    {
                        
    int i 0j;
                        
    // percorre cada caractere da url atraz das palavras reservadas para separação
                        // dos parâmetros
                        
    while (query.Length)
                        {
                            
    query.IndexOfAny(reservedi);
                            if (
    == -1)
                            {
                                
    urlEncoded.Append(query.Substring(iquery.Length i));
                                break;
                            }
                            
    urlEncoded.Append(query.Substring(ii));
                            
    urlEncoded.Append(query.Substring(j1));
                            
    1;
                        }
                        
    // codificando em UTF8 (evita que sejam mostrados códigos malucos em caracteres especiais
                        
    byteBuffer Encoding.UTF8.GetBytes(urlEncoded.ToString());

                        
    request.ContentLength byteBuffer.Length;
                        
    requestStream request.GetRequestStream();
                        
    requestStream.Write(byteBuffer0byteBuffer.Length);
                        
    requestStream.Close();
                    }
                    else
                    {
                        
    request.ContentLength 0;
                    }

                    
    // Dados recebidos 
                    
    response request.GetResponse();
                    
    Stream responseStream response.GetResponseStream();

                    
    // Codifica os caracteres especiais para que possam ser exibidos corretamente
                    
    System.Text.Encoding encoding System.Text.Encoding.Default;

                    
    // Preenche o reader
                    
    reader = new StreamReader(responseStreamencoding);

                    
    Char[] charBuffer = new Char[256];
                    
    int count reader.Read(charBuffer0charBuffer.Length);

                    
    StringBuilder Dados = new StringBuilder();

                    
    // Lê cada byte para preencher meu stringbuilder
                    
    while (count 0)
                    {
                        
    Dados.Append(new String(charBuffer0count));
                        
    count reader.Read(charBuffer0charBuffer.Length);
                    }

                    
    // Imprimo o que recebi
                    
    Console.Write(Dados);
                }
                catch (
    Exception e)
                {
                    
    // Ocorreu algum erro
                    
    Console.Write("Erro: " e.Message);
                }
                finally
                {
                    
    // Fecha tudo
                    
    if (requestStream != null)
                        
    requestStream.Close();
                    if (
    response != null)
                        
    response.Close();
                    if (
    reader != null)
                        
    reader.Close();
                }
            }
        }

    ~# Criado pela [IN]Segurança #~
X
Working...
X