2009-07-16 21 views
10

Sto avendo un momento ridicolo cercando di ottenere un API SMS funzionante (ZeepMobile, se sei interessato) con .NET ... Sono stato in giro su .NET per alcuni anni, ma con tutta questa roba di social networking e API, ho bisogno di entrare un po 'in HttpWebRequest. Sono nuovo, ma non completamente nuovo; Sono stato in grado di collegare il mio sito a Twitter senza troppe storie (cioè, sono stato in grado di modificare il codice di qualcuno per funzionare per me).Gestione degli errori da HttpWebRequest.GetResponse

In ogni caso, il modo in cui funziona l'API è inviare un messaggio SMS, inviare loro un POST e rispondono a te. Posso inviarlo bene, ma ogni volta che faccio, piuttosto che restituire qualcosa di utile per capire qual è l'errore, ottengo la Yellow Error Page Of Death (YEPOD) che dice qualcosa all'effetto di "Il server remoto ha restituito un errore: (400) Richiesta non valida. " Ciò si verifica sulla mia linea:

'...creation of httpwebrequest here...' 
Dim myWebResponse As WebResponse 
myWebResponse = request.GetResponse() '<--- error line 

Esiste un modo per ricevere semplicemente l'errore dal server piuttosto che avere il server web un'eccezione e mi danno la YEPOD?

O meglio ancora, qualcuno può pubblicare un esempio funzionante del proprio codice Zeep? :)

Grazie!

EDIT: Ecco tutta la mia blocco di codice:

Public Shared Function SendTextMessage(ByVal username As String, _ 
ByVal txt As String) As String 
    Dim content As String = "user_id=" + _ 
username + "&body=" + Current.Server.UrlEncode(txt) 

    Dim httpDate As String = DateTime.Now.ToString("r") 
    Dim canonicalString As String = API_KEY & httpDate & content 

    Dim encoding As New System.Text.UTF8Encoding 
    Dim hmacSha As New HMACSHA1(encoding.GetBytes(SECRET_ACCESS_KEY)) 

    Dim hash() As Byte = hmacSha.ComputeHash(encoding.GetBytes(canonicalString)) 
    Dim b64 As String = Convert.ToBase64String(hash) 

    'connect with zeep' 
    Dim request As HttpWebRequest = CType(WebRequest.Create(_ 
"https://api.zeepmobile.com/messaging/2008-07-14/send_message"), HttpWebRequest) 
    request.Method = "POST" 
    request.ServicePoint.Expect100Continue = False 

    ' set the authorization levels' 
    request.Headers.Add("Authorization", "Zeep " & API_KEY & ":" & b64) 
    request.ContentType = "application/x-www-form-urlencoded" 
    request.ContentLength = content.Length 

    ' set up and write to stream' 
    Dim reqStream As New StreamWriter(request.GetRequestStream()) 
    reqStream.Write(content) 
    reqStream.Close() 
    Dim msg As String = "" 
    msg = reqStream.ToString 

    Dim myWebResponse As WebResponse 
    Dim myResponseStream As Stream 
    Dim myStreamReader As StreamReader 

    myWebResponse = request.GetResponse() 

    myResponseStream = myWebResponse.GetResponseStream() 
    myStreamReader = New StreamReader(myResponseStream) 
    msg = myStreamReader.ReadToEnd() 
    myStreamReader.Close() 
    myResponseStream.Close() 

    ' Close the WebResponse' 
    myWebResponse.Close() 
    Return msg 
End Function 
+0

ps, ​​c'è un modo per visualizzare solo quello che le intestazioni sono sia l'invio e la ricezione? sto cercando di usare il violinista, ma o non so come usarlo o è completamente inutile ... – Jason

+0

Si prega di fornire il codice di richiesta – cdm9002

+0

ps - per coloro che cercano di far funzionare il codice zeep, il codice di cui sopra restituisce una 400 Bad Request: "Il tempo del messaggio differisce di molto dall'orologio del server o l'intestazione della Data non è stata fornita." Sto ancora lavorando su questo, dato che non puoi modificare l'intestazione "Date" ... – Jason

risposta

22

Prova questo:

Dim req As HttpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest) 
'' set up request 
Try 
    Using response = req.GetResponse() 
     '' success in here 
    End Using 
Catch ex As WebException 
    Console.WriteLine(ex.Status) 
    If ex.Response IsNot Nothing Then 
     '' can use ex.Response.Status, .StatusDescription 
     If ex.Response.ContentLength <> 0 Then 
      Using stream = ex.Response.GetResponseStream() 
       Using reader = New StreamReader(stream) 
        Console.WriteLine(reader.ReadToEnd()) 
       End Using 
      End Using 
     End If 
    End If 
End Try 

C# versione

HttpWebRequest req = (HttpWebRequest) WebRequest.Create(url); 
// set up request 
try { 
    using (var response = req.GetResponse()) { 
     // success in here 
     } 
} 
catch (WebException ex) { 
    Console.WriteLine(ex.Status); 
    if (ex.Response != null) { 
     // can use ex.Response.Status, .StatusDescription 
     if (ex.Response.ContentLength != 0) { 
      using (var stream = ex.Response.GetResponseStream()) { 
       using (var reader = new StreamReader(stream)) { 
        Console.WriteLine(reader.ReadToEnd()); 
       } 
      } 
     } 
    }  
} 

Ecco il suo codice, modificato un po ':

Try 
    'connect with zeep' 
    Dim request As HttpWebRequest = CType(WebRequest.Create(_ 
"https://api.zeepmobile.com/messaging/2008-07-14/send_message"), HttpWebRequest) 
    request.Method = "POST" 
    request.ServicePoint.Expect100Continue = False 

    ' set the authorization levels' 
    request.Headers.Add("Authorization", "Zeep " & API_KEY & ":" & b64) 
    request.ContentType = "application/x-www-form-urlencoded" 
    request.ContentLength = content.Length 

    ' set up and write to stream' 
    Using requestStream As Stream = request.GetRequestStream() 
     Using requestWriter As New StreamWriter(requestStream) 
      requestWriter.Write(content) 
     End Using 
    End Using 

    Using myWebResponse As WebResponse = request.GetResponse() 
     Using myResponseStream As Stream = myWebResponse.GetResponseStream() 
      Using myStreamReader As StreamReader = New StreamReader(myResponseStream) 
       Return myStreamReader.ReadToEnd() 
      End Using 
     End Using 
    End Using 
Catch ex As WebException 
    Console.WriteLine(ex.Status) 
    If ex.Response IsNot Nothing Then 
     '' can use ex.Response.Status, .StatusDescription 
     If ex.Response.ContentLength <> 0 Then 
      Using stream = ex.Response.GetResponseStream() 
       Using reader = New StreamReader(stream) 
        Console.WriteLine(reader.ReadToEnd()) 
       End Using 
      End Using 
     End If 
    End If 
End Try 

intestazioni di dumping:

Dim headers As WebHeaderCollection = request.Headers 
' Displays the headers. Works with HttpWebResponse.Headers as well 
Debug.WriteLine(headers.ToString()) 

' And so does this 
For Each hdr As String In headers 
    Dim headerMessage As String = String.Format("{0}: {1}", hdr, headers(hdr)) 
    Debug.WriteLine(headerMessage) 
Next 
+0

ermm ... non sono così buono w/C# ... puoi tradurre in VB? – Jason

+0

Già lì. Mi dispiace –

+0

cosa fa "Uso" in VB? mai visto prima ... – Jason

1

Penso che sia normale per un WebException per essere gettato quando la richiesta restituisce un codice 4xx o 5xx. Hai solo bisogno di prenderlo e gestirlo in modo appropriato.

Hai guardato la collezione Headers dopo la chiamata a GetResponse?

it just throws an exception at the GetResponse... how would I check the headers after that?

Try 
    myWebResponse = request.GetResponse() 
Catch x As WebException 
    log, cleanup, etc. 
Finally 
    log/inspect headers? 
End Try 
+0

non riesco ad arrivare così lontano ... butta solo un'eccezione a GetResponse ... come potrei controllare le intestazioni dopo? – Jason

+0

Dal codice di errore 400 "richiesta errata", ho presupposto che l'eccezione fosse generata in risposta a un errore dell'altro server. Un errore nel tuo codice non produrrebbe un 500? –

+0

hai un codice effettivo per controllare le intestazioni? ho provato così tante cose ormai la mia testa è vorticosa ... grazie :( – Jason