root/lang/vb2005/FuwaKumo/trunk/FuwaKumo/WebAccessBase.vb @ 33664

Revision 33664, 7.6 kB (checked in by kiri_feather, 4 years ago)
Line 
1Imports System.Net
2
3Public MustInherit Class WebAccessBase
4    Protected Shared _proxy As System.Net.WebProxy = Nothing
5    Protected Shared _proxyType As ProxyTypeEnum = ProxyTypeEnum.IE
6    Protected Shared _defaultTimeOut As Integer = 20000
7
8    Public Enum ProxyTypeEnum
9        None
10        IE
11        Specified
12    End Enum
13
14    Protected Enum WEBACCESS_REQ_TYPE
15        ReqGET
16        ReqPOST
17    End Enum
18
19    Public Sub New()
20        ServicePointManager.Expect100Continue = False
21        With SettingNet.Instance
22            _proxyType = .ProxyType
23            _proxy = .Proxy
24            _defaultTimeOut = .TimeOut
25        End With
26    End Sub
27
28    Protected Shared Function CreateRequestObject(ByVal reqType As WEBACCESS_REQ_TYPE, _
29                                            ByVal url As System.Uri, _
30                                            ByVal param As System.Collections.Generic.SortedList(Of String, String)) As HttpWebRequest
31        Dim ub As New System.UriBuilder(url.AbsoluteUri)
32        If reqType = WEBACCESS_REQ_TYPE.ReqGET Then
33            ub.Query = CreateQueryString(param)
34        End If
35        Dim webReq As HttpWebRequest = CType(WebRequest.Create(ub.Uri), HttpWebRequest)
36        If reqType = WEBACCESS_REQ_TYPE.ReqGET Then
37            webReq.Method = "GET"
38        Else
39            webReq.Method = "POST"
40            webReq.ContentType = "application/x-www-form-urlencoded"
41            Using writer As New System.IO.StreamWriter(webReq.GetRequestStream)
42                writer.Write(CreateQueryString(param))
43            End Using
44        End If
45        webReq.Timeout = _defaultTimeOut
46        If _proxyType <> ProxyTypeEnum.IE Then webReq.Proxy = _proxy
47
48        Return webReq
49    End Function
50
51    Protected Shared Function CreateQueryString(ByVal param As System.Collections.Generic.SortedList(Of String, String)) As String
52        If param Is Nothing OrElse param.Count = 0 Then Return String.Empty
53
54        Dim query As New System.Text.StringBuilder
55        For Each key As String In param.Keys
56            query.AppendFormat("{0}={1}&", UrlEncode(key), UrlEncode(param(key)))
57        Next
58        Return query.ToString(0, query.Length - 1)
59    End Function
60
61    Protected Shared Function ParseQueryString(ByVal queryString As String) As System.Collections.Specialized.NameValueCollection
62        Dim query As New System.Collections.Specialized.NameValueCollection
63        Dim parts() As String = queryString.Split("&"c)
64        For Each part As String In parts
65            Dim index As Integer = part.IndexOf("="c)
66            If index = -1 Then
67                query.Add(Uri.UnescapeDataString(part), "")
68            Else
69                query.Add(Uri.UnescapeDataString(part.Substring(0, index)), Uri.UnescapeDataString(part.Substring(index + 1)))
70            End If
71        Next
72        Return query
73    End Function
74
75    Protected Shared Function UrlEncode(ByVal str As String) As String
76        Const _unreservedChars As String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~"
77        Dim sb As New System.Text.StringBuilder
78        Dim bytes As Byte() = System.Text.Encoding.UTF8.GetBytes(str)
79
80        For Each b As Byte In bytes
81            If _unreservedChars.IndexOf(Chr(b)) <> -1 Then
82                sb.Append(Chr(b))
83            Else
84                sb.appendformat("%{0:X2}", b)
85            End If
86        Next
87        Return sb.ToString()
88    End Function
89
90    Private Shared Function GetResponse(Of T)(ByVal webRequest As HttpWebRequest, _
91                                        ByRef statusCode As HttpStatusCode, _
92                                        ByVal encode As System.Text.Encoding, _
93                                        ByVal headerInfo As System.Collections.Specialized.NameValueCollection _
94                                    ) As T
95
96        Dim webRes As HttpWebResponse = Nothing
97        Try
98            webRes = CType(webRequest.GetResponse(), HttpWebResponse)
99
100            If headerInfo IsNot Nothing AndAlso headerInfo.Count > 0 Then
101                For Each key As String In headerInfo.Keys
102                    If Array.IndexOf(webRes.Headers.AllKeys, key) > -1 Then
103                        headerInfo(key) = webRes.Headers.Item(key)
104                    Else
105                        headerInfo(key) = ""
106                    End If
107                Next
108            End If
109
110            statusCode = webRes.StatusCode
111            If statusCode = HttpStatusCode.MovedPermanently OrElse _
112               statusCode = HttpStatusCode.Found OrElse _
113               statusCode = HttpStatusCode.SeeOther OrElse _
114               statusCode = HttpStatusCode.TemporaryRedirect Then
115                If GetType(T).Name = GetType(String).Name Then
116                    Return CType(webRes.Headers.Item("Location"), Object)
117                Else
118                    Return Nothing
119                End If
120            End If
121
122            Using strm As System.IO.Stream = webRes.GetResponseStream()
123                Select Case GetType(T).Name
124                    Case GetType(System.Drawing.Bitmap).Name
125                        Return CType(New System.Drawing.Bitmap(strm), Object)
126                    Case GetType(String).Name
127                        Using sr As New System.IO.StreamReader(strm, encode)
128                            Return CType(sr.ReadToEnd(), Object)
129                        End Using
130                    Case Else
131                        Throw New System.ArgumentException("Type must String or Bitmap")
132                End Select
133            End Using
134        Catch ex As System.Net.WebException
135            Throw
136        Catch ex As Exception
137
138        Finally
139            If webRes IsNot Nothing Then
140                webRes.Close()
141            End If
142        End Try
143    End Function
144
145    Protected Shared Function GetText(ByVal webRequest As HttpWebRequest, _
146                                        ByRef statusCode As HttpStatusCode, _
147                                        ByVal encode As System.Text.Encoding, _
148                                        ByVal headerInfo As System.Collections.Specialized.NameValueCollection _
149                                    ) As String
150        Try
151            Return GetResponse(Of String)(webRequest, statusCode, encode, headerInfo)
152        Catch ex As Exception
153            Throw
154        End Try
155    End Function
156
157    Protected Shared Function GetText(ByVal webRequest As HttpWebRequest, _
158                                        ByRef statusCode As HttpStatusCode, _
159                                        ByVal headerInfo As System.Collections.Specialized.NameValueCollection _
160                                    ) As String
161        Try
162            Return GetText(webRequest, statusCode, System.Text.Encoding.UTF8, headerInfo)
163        Catch ex As Exception
164            Throw
165        End Try
166    End Function
167
168    Protected Shared Function GetText(ByVal webRequest As HttpWebRequest, _
169                                        ByRef statusCode As HttpStatusCode _
170                                    ) As String
171        Try
172            Return GetText(webRequest, statusCode, Nothing)
173        Catch ex As Exception
174            Throw
175        End Try
176    End Function
177
178    Protected Shared Function GetImage(ByVal webRequest As HttpWebRequest, _
179                                        ByRef statusCode As HttpStatusCode _
180                                    ) As System.Drawing.Bitmap
181        Try
182            Return GetResponse(Of System.Drawing.Bitmap)(webRequest, statusCode, Nothing, Nothing)
183        Catch ex As Exception
184            Throw
185        End Try
186    End Function
187End Class
Note: See TracBrowser for help on using the browser.