HELP: Using WebRequest to POST

Zoopnfunk

Member
Joined
Nov 1, 2005
Messages
5
Programming Experience
1-3
The page I would like to interact with has the following inputs when I view the source:

<form action="/index.php" method="post">
<input type="hidden" name="ac" value="raubzug">
<input type="hidden" name="sac" value="attack">
<input type="hidden" name="gegnerid" value="115021541">
<input type="image" src="img/lang/EN/btn_angriff.jpg">

So, instead of clicking on the button that is this page I want to automate it through vb.net. From what I have read, I need to use teh webRequest object set to POST. However, when I try to run my application I get the following error on the line where I declare my StreamWriter:

"An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll

Additional information: Stream was not writable."

Here is my code:

VB.NET:
Private Sub hitPlayerAlt(ByVal strPlayerID As String)
		Dim postData As String
		postData = "ac=raubzug&sac=attack&gegnerid=" & strPlayerID

		Dim request As WebRequest = WebRequest.Create("http://world5.knightfight.co.uk/index.php?ac=raubzug")
		request.Method = "POST"
		request.ContentType = "application/x-www-form-encoded"

		''// Send the Post Data
		Dim sw As StreamWriter = New StreamWriter(request.GetRequestStream)
		sw.WriteLine(postData)

		''// Read the Response
		Dim wr As WebResponse = request.GetResponse
		Dim sr As StreamReader = New StreamReader(wr.GetResponseStream)
		Dim responseText As String = sr.ReadToEnd
	End Sub

Can anyone help me? I am not sure what I am doing wrong... I have tried a few different approaches now.

Thanks,

zoop
 
HTTPWebRequest POST : multiple POSTs

I followed a tutorial to create an EasyHttp class (source below) and with some tweaking I am able to use my application to send a POST using HTTPWebRequest. Now I have an issue when I try to send successive posts to the server.

On the second POST attempt I get the following error message:

"Stream was not writable."

In each iteration the only thing that changes is the PlayerID in the POST data that I am sending to the server. I have tested all of the playerID's in my list with the application and each of them will run one if they are first in the list (contained in my listView) -- but the application always fails when it reaches the second value in my list.

Here is my code that calls my EasyHttp helper class:

VB.NET:
'// Attack each player in the lvHitList
	Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
		Dim strPlayerID As String
		lvHitList.HideSelection = False
		For itemIndex As Integer = 0 To lvHitList.Items.Count - 1
			'// Define PlayerID to Attack
			strPlayerID = lvHitList.Items(itemIndex).SubItems(1).Text()

			'// Highlight Selected Item in ListView
			lvHitList.Items(itemIndex).Selected = True
			lvHitList.Items(itemIndex).Focused = True
			lvHitList.Refresh()

			'//	Attack Player at Selected itemIndex
			attackPlayer(strPlayerID, itemIndex)
		Next
	End Sub

	'// Attack Player 
	Private Sub attackPlayer(ByVal strPlayerID As String, ByVal itemIndex As Integer)
		Dim kfHelper As New EasyHttp
		Dim strResult As String
		strResult = kfHelper.Send("http://world5.knightfight.co.uk/index.php?ac=raubzug", _
"ac=raubzug&sac=attack&gegnerid=" & strPlayerID, EasyHttp.HTTPMethod.HTTP_POST)

		'// Parse strResult & wait on Next Attack
		If strResult.IndexOf("Winner:") > -1 Then
			lvHitList.Items(itemIndex).SubItems(2).Text = "Yes"
			System.Threading.Thread.Sleep(300000)
		Else
			System.Threading.Thread.Sleep(5000)
		End If
	End Sub

And here is the modified EasyHttp helper class:

VB.NET:
' EasyHttp.vb class file
Public Class EasyHttp
	Public Enum HTTPMethod As Short
		HTTP_GET = 0
		HTTP_POST = 1
	End Enum

	Public Function Send(ByVal URL As String, _
	Optional ByVal PostData As String = "", _
	Optional ByVal Method As HTTPMethod = HTTPMethod.HTTP_GET, _
	Optional ByVal ContentType As String = "") As String

		Dim Request As HttpWebRequest = CType(WebRequest.Create(URL), HttpWebRequest)
		Dim Response As HttpWebResponse
		Dim SW As StreamWriter
		Dim SR As StreamReader
		Dim ResponseData As String
		System.Net.ServicePointManager.Expect100Continue = False

		' Prepare Request Object
		Request.Referer = "http://world5.knightfight.co.uk/"		'index.php?ac=raubzug
		Request.Method = Method.ToString().Substring(5)

		' Set form/post content-type if necessary
		If (Method = HTTPMethod.HTTP_POST AndAlso PostData <> "" AndAlso ContentType = "") Then
			ContentType = "application/x-www-form-urlencoded"
		End If

		' Set Content-Type
		If (ContentType <> "") Then
			Request.ContentType = ContentType
			'//	Request.ContentLength = PostData.Length
		End If

		'// Establish Authentication Cookie
		Dim cookieUserName As System.Net.Cookie = New System.Net.Cookie("mg_user", "myUsername")
		cookieUserName.Domain = "world5.knightfight.co.uk"
		Dim cookiePassword As System.Net.Cookie = New System.Net.Cookie("mg_password", "myPassword")
		cookiePassword.Domain = "world5.knightfight.co.uk"
		Dim cc As CookieContainer = New CookieContainer
		cc.Add(cookieUserName)
		cc.Add(cookiePassword)
		Request.CookieContainer = cc


		' Send Request, If Request
		If (Method = HTTPMethod.HTTP_POST) Then
			Try
				SW = New StreamWriter(Request.GetRequestStream())
				SW.Write(PostData)
			Catch Ex As Exception
				Throw Ex
			Finally
				SW.Close()
			End Try
		End If

		' Receive Response
		Try
			'//
			Method = HTTPMethod.HTTP_POST
			Request.Method = Method.ToString().Substring(5)
			'//
			Response = CType(Request.GetResponse(), HttpWebResponse)
			SR = New StreamReader(Response.GetResponseStream())
			ResponseData = SR.ReadToEnd()
		Catch Wex As System.Net.WebException
			SR = New StreamReader(Wex.Response.GetResponseStream())
			ResponseData = SR.ReadToEnd()
			Throw New Exception(ResponseData)
		Finally
			SR.Close()
		End Try


		Return ResponseData
	End Function
End Class

I just can't seem to figure out why my HelperClass performs as expected during the first iteration and not during the second. I am creating a new instance of the class on each pass, so I don't know why it should behave any differently.

Is there a method for releasing the first connection that I am missing? Any suggestions at all?

I am getting very close here. I can execute my code for any single 'PlayerID' but I can't get it working for a list, or array of them. Please Help!! :)
 
Back
Top