2012-08-08 19 views
12

Sto cercando di creare un socket HTTP request. Il mio codice è il seguente:C#: come eseguire una richiesta HTTP utilizzando i socket?

using System; 
using System.Net; 
using System.Net.Sockets; 
using System.Text; 
class test 
{ 
    public static void Main(String[] args) 
    { 
     string hostName = "127.0.0.1"; 
     int hostPort = 9887; 
     int response = 0; 

     IPAddress host = IPAddress.Parse(hostName); 
     IPEndPoint hostep = new IPEndPoint(host, hostPort); 
     Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 

     sock.Connect(hostep); 

     string request_url = "http://127.0.0.1/register?id=application/vnd-fullphat.test&title=My%20Test%20App"; 
     response = sock.Send(Encoding.UTF8.GetBytes(request_url)); 
     response = sock.Send(Encoding.UTF8.GetBytes("\r\n")); 

     bytes = sock.Receive(bytesReceived, bytesReceived.Length, 0); 
     page = page + Encoding.ASCII.GetString(bytesReceived, 0, bytes); 
     Console.WriteLine(page); 
     sock.Close(); 
    } 
} 

Ora, quando eseguo il codice di cui sopra non succede nulla mentre quando inserisco il mio request_url browser ricevo una notifica da Ringhio dicendo che Application Registered e la risposta che ricevo da Browser è

SNP/2.0/0/OK/556 

La risposta che ottengo dal mio codice è SNP/3.0/107/BadPacket.

Quindi, cosa c'è di sbagliato nel mio codice.

Snarl Request format specification

+1

C'è un motivo per cui è necessario utilizzare Socket anziché, ad esempio, "System.Net.Http.HttpClient"? –

+2

o Webclient per quella materia ... – steveg89

+0

Nessun motivo specifico. In realtà non ero a conoscenza di 'HttpCLient o Webclient'. Ma comunque mi piacerebbe capire cosa è il mio codice precedente. – RanRag

risposta

7

È necessario includere il contenuto di lunghezza e doppia nuova linea alla fine per indicare fine dell'intestazione.

var request = "GET /register?id=application/vnd-fullphat.test&title=My%20Test%20App HTTP/1.1\r\n" + 
    "Host: 127.0.0.1\r\n" + 
    "Content-Length: 0\r\n" + 
    "\r\n"; 

Le specifiche HTTP 1.1 può essere trovato qui: http://www.w3.org/Protocols/rfc2616/rfc2616.html

+0

Grazie amico. Proprio quello che stavo cercando. – kurt

1

La tua richiesta non è corretta. Secondo wikipedia, a HTTP Get request deve assomigliare a:

string request = "GET /register?id=application/vnd-fullphat.test&title=My%20Test%20App HTTP/1.1\r\nHost: 127.0.0.1\r\n"; 
+0

Ricevo ancora 'SNP/3.0/107/BadPacket' – RanRag

+3

Sembra che tu abbia bisogno di qualcosa di più nella tua richiesta, come Connessione, Accetta o forse Accetta-Codifica. Quello che PVitt ha mostrato è una richiesta minima, anche se potrebbe non essere sufficiente per il tuo protocollo specifico. Prova a lavorare con WebClient come suggerito sopra e vedi se funziona così sei sicuro che l'API funzioni come dovrebbe. –

+0

Secondo la risposta accettata, deve essere stato "Content-Length". – vapcguy

13

Io so niente di SNP. Il tuo codice è un po 'confuso sulla parte di ricezione. Ho usato l'esempio seguente per inviare e leggere la risposta del server per una richiesta HTTP GET. Diamo prima un'occhiata alla richiesta e poi esaminiamo la risposta.

richiesta HTTP GET:

GET/HTTP/1.1 
Host: 127.0.0.1 
Connection: keep-alive 
Accept: text/html 
User-Agent: CSharpTests 

string - "GET/HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: keep-alive\r\nAccept: text/html\r\nUser-Agent: CSharpTests\r\n\r\n" 

Server intestazione della risposta HTTP:

HTTP/1.1 200 OK 
Date: Sun, 07 Jul 2013 17:13:10 GMT 
Server: Apache/2.4.4 (Win32) OpenSSL/0.9.8y PHP/5.4.16 
Last-Modified: Sat, 30 Mar 2013 11:28:59 GMT 
ETag: \"ca-4d922b19fd4c0\" 
Accept-Ranges: bytes 
Content-Length: 202 
Keep-Alive: timeout=5, max=100 
Connection: Keep-Alive 
Content-Type: text/html 

string - "HTTP/1.1 200 OK\r\nDate: Sun, 07 Jul 2013 17:13:10 GMT\r\nServer: Apache/2.4.4 (Win32) OpenSSL/0.9.8y PHP/5.4.16\r\nLast-Modified: Sat, 30 Mar 2013 11:28:59 GMT\r\nETag: \"ca-4d922b19fd4c0\"\r\nAccept-Ranges: bytes\r\nContent-Length: 202\r\nKeep-Alive: timeout=5, max=100\r\nConnection: Keep-Alive\r\nContent-Type: text/html\r\n\r\n" 

ho volutamente ommited il corpo della risposta del server, perché sappiamo già che è esattamente 202 byte, come specificato per Content-Length nell'intestazione della risposta.

Un'occhiata alle specifiche HTTP rivelerà che un'intestazione HTTP termina con una nuova riga vuota ("\ r \ n \ r \ n"). Quindi dobbiamo solo cercarlo.

Vediamo un po 'di codice in azione. Assumere un socket variabile di tipo System.Net.Sockets.Socket.

socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
socket.Connect("127.0.0.1", 80); 
string GETrequest = "GET/HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: keep-alive\r\nAccept: text/html\r\nUser-Agent: CSharpTests\r\n\r\n"; 
socket.Send(Encoding.ASCII.GetBytes(GETrequest)); 

Abbiamo inviato la richiesta al server, riceviamo e analizziamo correttamente la risposta.

bool flag = true; // just so we know we are still reading 
string headerString = ""; // to store header information 
int contentLength = 0; // the body length 
byte[] bodyBuff = new byte[0]; // to later hold the body content 
while (flag) 
{ 
// read the header byte by byte, until \r\n\r\n 
byte[] buffer = new byte[1]; 
socket.Receive(buffer, 0, 1, 0); 
headerString += Encoding.ASCII.GetString(buffer); 
if (headerString.Contains("\r\n\r\n")) 
{ 
    // header is received, parsing content length 
    // I use regular expressions, but any other method you can think of is ok 
    Regex reg = new Regex("\\\r\nContent-Length: (.*?)\\\r\n"); 
    Match m = reg.Match(headerString); 
    contentLength = int.Parse(m.Groups[1].ToString()); 
    flag = false; 
    // read the body 
    bodyBuff = new byte[contentLength]; 
    socket.Receive(bodyBuff, 0, contentLength, 0); 
} 
} 
Console.WriteLine("Server Response :"); 
string body = Encoding.ASCII.GetString(bodyBuff); 
Console.WriteLine(body); 
socket.Close(); 

Questo è probabilmente il metodo peggiore per fare questo in C#, ci sono tonnellate di classi per gestire le richieste HTTP e le risposte in .NET, ma ancora se avete bisogno, funziona.

0

Il requisito minimo per una richiesta HTTP è "GET/HTTP/1.0 \ r \ n \ r \ n" (se la rimozione dell'Host è consentita). Ma in SNARL, è necessario inserire la lunghezza del contenuto (ciò che ho sentito di più).

Quindi,

 Socket sck = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp); 

     sck.Connect(ip, port); 
     sck.Send(Encoding.UTF8.GetBytes("THE HTTP REQUEST HEADER")); 
     Console.WriteLine("SENT"); 
     string message = null; 
     byte[] bytesStored = new byte[ReceiveBufferSize]; 
     int k1 = sck.Receive(bytesStored); 
     for (int i = 0; i < k1; i++) 
     { 
      message = message + Convert.ToChar(bytesStored[i]).ToString(); 
     } 
     Console.WriteLine(message); // PRINT THE RESPONSE 

EDIT: Sono profondamente dispiaciuto per il precedente risposta poveri. Non è stato formulato e ho aggiunto l'idea/soluzione principale della risposta (nessuna informazione semplice). Inoltre, ho aggiunto il codice sorgente.

Ho testato su diversi siti e funziona perfettamente. Se non ha funzionato, dovresti correggerlo aggiungendo altra intestazione (soluzione più probabile).

Problemi correlati