Skip to content

Instantly share code, notes, and snippets.

@jz5
Last active Aug 29, 2015
Embed
What would you like to do?
Sub Main()
' ログインして Cookie 取得
Dim cookies = Login("スクリーンネームまたはメールアドレス", "パスワード")
' 取得した Cookie を付けてアカウント設定ページにアクセス
Dim url = "https://twitter.com/settings/account"
Dim req = WebRequest.CreateHttp(New Uri(url))
req.CookieContainer = New CookieContainer
req.CookieContainer.Add(cookies)
Dim html As String
Using res = req.GetResponse
Using rs = res.GetResponseStream
Using sr = New StreamReader(rs)
html = sr.ReadToEnd
End Using
End Using
End Using
End Sub
Private Function GetAuthenticityTokenAndCookies() As Tuple(Of String, CookieCollection)
Dim req = WebRequest.CreateHttp("https://twitter.com/")
req.Method = "GET"
req.ServicePoint.Expect100Continue = False
req.CookieContainer = New CookieContainer
Using res = DirectCast(req.GetResponse, HttpWebResponse)
Dim html As String
Using rs = res.GetResponseStream
Using sr = New IO.StreamReader(rs, Encoding.UTF8)
html = sr.ReadToEnd
End Using
End Using
html = html.Substring(html.IndexOf("action=""https://twitter.com/sessions"""))
Dim m = Regex.Match(html, "value=""(?<token>.*?)""\s+name=""authenticity_token""")
Return New Tuple(Of String, CookieCollection)(m.Groups("token").Value, res.Cookies)
End Using
End Function
Private Function Login(name As String, password As String) As CookieCollection
Dim val = GetAuthenticityTokenAndCookies()
Dim token = val.Item1
Dim cookies = val.Item2
Dim param = String.Format("session%5Busername_or_email%5D={0}&session%5Bpassword%5D={1}&remember_me=0&return_to_ssl=true&scribe_log=&redirect_after_login=%2F&authenticity_token={2}", name, password, token)
Dim buf = Text.Encoding.ASCII.GetBytes(param)
Dim uri = New Uri("https://twitter.com/sessions")
Dim req = WebRequest.CreateHttp(uri)
req.Method = "POST"
req.ContentType = "application/x-www-form-urlencoded"
req.ContentLength = buf.Length
req.Referer = "https://twitter.com/"
req.ServicePoint.Expect100Continue = False
req.CookieContainer = New CookieContainer
If cookies IsNot Nothing Then
req.CookieContainer.Add(cookies)
End If
Using rs = req.GetRequestStream
rs.Write(buf, 0, buf.Length)
End Using
Dim html As String
Using res = req.GetResponse
Using rs = res.GetResponseStream
Using sr = New StreamReader(rs, Encoding.UTF8)
html = sr.ReadToEnd
End Using
End Using
Return req.CookieContainer.GetCookies(uri)
End Using
End Function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment