处理来自HttpWebRequest.GetResponse的错误

时间:2009-07-16 20:23:51

标签: asp.net vb.net httpwebrequest sms

我有一个荒谬的时间试图让一个SMS API工作(ZeepMobile,如果你有兴趣)用.NET ...我已经在.NET上工作了几年,但是所有这些社交网络和API的东西,我需要进入HttpWebRequest一点。我是新手,但不是全新的;我能够将我的网站连接到Twitter而不用太大惊小怪(即,我能够修改某人的代码以便为我工作)。

无论如何,他们的API工作方式是发送短信,你发送一个POST,然后他们回复你。我可以发送它很好,但每次我做,而不是回应一些有用的东西来弄清楚错误是什么,我得到黄色错误死亡页面(YEPOD)说“远程服务器返回一个效果错误:(400)错误请求。“这发生在我的行上:

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

有没有办法简单地从服务器接收错误而不是让网络服务器抛出异常并给我YEPOD?

或者更好的是,任何人都可以发布他们的Zeep代码的工作示例吗? :)

谢谢!

编辑:这是我的整个代码块:

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

2 个答案:

答案 0 :(得分:23)

试试这个:

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#版

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());
                }
            }
        }
    }    
}

这是您的代码,稍作修改:

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

转储标题:

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

答案 1 :(得分:1)

我认为当请求返回4xx或5xx代码时抛出WebException是正常的。你只需要抓住它并妥善处理它。

在致电Headers后,您是否看过GetResponse收藏品?

  

它只是在GetResponse上抛出一个异常......之后如何检查标题?

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