2011-10-26 23 views
13

Ciao provo a scrivere una richiesta HTTP in C# (Post), ma ho bisogno di aiuto con un erroreCome scrivere una richiesta HTTP

Expl: Voglio inviare il contenuto di un file DLC al server e ricevere il contenuto decrittografato.

C# Codice

public static void decryptContainer(string dlc_content) 
{ 
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://dcrypt.it/decrypt/paste"); 
    request.Method = "POST"; 
    request.ContentType = "application/x-www-form-urlencoded"; 
    request.Accept = "Accept=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; 

    using (StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII)) 
    { 
     writer.Write("content=" + dlc_content); 
    } 

    HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 

    using (StreamReader reader = new StreamReader(response.GetResponseStream())) 
    { 
     Console.WriteLine(reader.ReadToEnd()); 
    } 
} 

e qui ho avuto la richiesta html

<form action="/decrypt/paste" method="post"> 
    <fieldset> 
     <p class="formrow"> 
      <label for="content">DLC content</label> 
      <input id="content" name="content" type="text" value="" /> 
     </p> 
     <p class="buttonrow"><button type="submit">Submit »</button></p> 
    </fieldset> 
</form> 

messaggio di errore:

{ 
    "form_errors": { 
     "__all__": [ 
     "Sorry, an error occurred while processing the container." 
     ] 
    } 
} 

sarebbe molto utile se qualcuno potesse aiutarmi a risolvere il problema!

+0

http://codesamplez.com/programming/http-request-c-sharp – happy

risposta

14

Non è stata impostata una lunghezza del contenuto, che potrebbe causare problemi. Si potrebbe anche provare a scrivere byte direttamente nel flusso, invece di convertirlo in ASCII prima .. (farlo nel modo opposto a come si sta facendo in questo momento), ad esempio:

public static void decryptContainer(string dlc_content) 
    { 
     HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://dcrypt.it/decrypt/paste"); 
     request.Method = "POST"; 
     request.ContentType = "application/x-www-form-urlencoded"; 
     request.Accept = "Accept=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; 

     byte[] _byteVersion = Encoding.ASCII.GetBytes(string.Concat("content=", dlc_content)); 

     request.ContentLength = _byteVersion.Length 

     Stream stream = request.GetRequestStream(); 
     stream.Write(_byteVersion, 0, _byteVersion.Length); 
     stream.Close(); 

     HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 

     using (StreamReader reader = new StreamReader(response.GetResponseStream())) 
     { 
      Console.WriteLine(reader.ReadToEnd()); 
     } 
    } 

Ho personalmente trovato posting come questo per essere un po '"fiducioso" in passato. Si potrebbe anche provare a impostare ProtocolVersion sulla richiesta.

0

di ricevere flussi associato alla risposta prima poi passare che nel StreamReader come di seguito:

Stream receiveStream = response.GetResponseStream();  

    using (StreamReader reader = new StreamReader(receiveStream, Encoding.ASCII)) 
    { 
     Console.WriteLine(reader.ReadToEnd()); 
    } 
1

Un problema che vedo subito è che è necessario a URL valore di codifica del parametro content. Utilizzare HttpUtility.UrlEncode() per quello. Oltre a ciò ci potrebbero essere altri problemi, ma è difficile dire che non sappia che servizio fa. L'errore è troppo generico e potrebbe significare qualsiasi cosa

6

vorrei semplificare il codice, come questo:

public static void decryptContainer(string dlc_content) 
{ 
    using (var client = new WebClient()) 
    { 
     var values = new NameValueCollection 
     { 
      { "content", dlc_content } 
     }; 
     client.Headers[HttpRequestHeader.Accept] = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; 
     string url = "http://dcrypt.it/decrypt/paste"; 
     byte[] result = client.UploadValues(url, values); 
     Console.WriteLine(Encoding.UTF8.GetString(result)); 
    } 
} 

Inoltre, garantisce che i parametri di richiesta siano correttamente codificati.

+0

Inoltre assicura che i parametri sono codificati più o meno correttamente. Vedi http://stackoverflow.com/a/10836145/4136325 –

+0

Esempio molto leggero. Grazie. +1 –

+0

Quale webClient hai usato? –

1

request.ContentLength deve essere impostato.

Inoltre, c'è un motivo per cui si codifica ASCII rispetto a UTF8?

+0

HttpWebRequest imposta ContentLength per impostazione predefinita. application/x-www-form-urlencoded sarà sempre nell'intervallo ASCII, quindi è identico tra entrambe le codifiche. –

2
public string void decryptContainer(string dlc_content) //why not return a string, let caller decide what to do with it. 
{ 
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://dcrypt.it/decrypt/paste"); 
    request.Method = "POST"; 
    request.ContentType = "application/x-www-form-urlencoded"; 
    request.Accept = "Accept=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";//sure this is needed? Maybe just match the one content-type you expect. 
    using (StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII)) 
    { 
     writer.Write("content=" + Uri.EscapeDataString(dlc_content));//escape the value of dlc_content so that the entity sent is valid application/x-www-form-urlencoded 
    } 
    using(HttpWebResponse response = (HttpWebResponse)request.GetResponse())//this should be disposed when finished with. 
    using (StreamReader reader = new StreamReader(response.GetResponseStream())) 
    { 
     return reader.ReadToEnd(); 
    } 
} 

Ci potrebbe ancora essere un problema con ciò che viene effettivamente inviato.

0

Come non posso commentare la soluzione di Jon Hanna. Ciò ha risolto per me: Uri.EscapeDataString

 // this is what we are sending 
     string post_data = "content=" + Uri.EscapeDataString(dlc_content); 

     // this is where we will send it 
     string uri = "http://dcrypt.it/decrypt/paste"; 

     // create a request 
     HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); 
     request.KeepAlive = false; 
     request.ProtocolVersion = HttpVersion.Version10; 
     request.Method = "POST"; 

     // turn our request string into a byte stream 
     byte[] postBytes = Encoding.ASCII.GetBytes(post_data); 

     // this is important - make sure you specify type this way 
     request.ContentType = "application/x-www-form-urlencoded"; 
     request.ContentLength = postBytes.Length; 

     Stream requestStream = request.GetRequestStream(); 

     // now send it 
     requestStream.Write(postBytes, 0, postBytes.Length); 
     requestStream.Close(); 

     // grab te response and print it out to the console along with the status code 
     HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
     Console.WriteLine(new StreamReader(response.GetResponseStream()).ReadToEnd()); 
     Console.WriteLine(response.StatusCode); 
Problemi correlati