Windows Develop Bookmark and Share   
 index > Windows Forms General > How to call a web page as Post method from Windows Form Application?
 

How to call a web page as Post method from Windows Form Application?

I have a form application with some TextBox controls in it.I want to send the values of these controls as Post variables to the web page.

I can call a web page using System.Diagnostics.Process.Start("Http://...") but how to make a call like it was called from form element with method post?
msmuser  Sunday, September 10, 2006 3:50 PM

Hi msmuser, I dont really understand what u want to achieve but here is one way of doing it if u dont need to open any browser, just send your data via POST method.


// Using WebRequest to send data to a website
WebRequest request = WebRequest.Create("http://blabla.com/answer.aspx");

//Set method property
request.Method = "POST";
//Create POST data
string postData = "myfirstdata=" + TextBox1.Text + "&myseconddata=" + TextBox2.Text;
//and convert it to byte array
byte[] dataBuffer = System.Text.Encoding.UTF8.GetBytes(postData);
//Set ContentType property of the request
request.ContentType = "application/x-www-form-urlencoded";
//Set ContentLength property of the request
request.ContentLength = dataBuffer.Length

//Get request stream
Stream postStream = request.GetRequestStream();
//Write data to request stream
postStream.Write(dataBuffer, 0, dataBuffer.Length);
//Close stream object
postStream.Close();

And then if u need to get response, just use WebResponse class and make use of the response stream.

Hope this helps.

Shah

shahrul  Monday, September 11, 2006 6:30 AM
you can't really, not unless you maybe use the HttpWebRequest/response classes. But even then I'm not sure.
ahmedilyas  Sunday, September 10, 2006 4:18 PM
Is there a way to do this if I use WebBrowser class?Like create a form/submit page with hidden varibles in it?
So only submit button should be visible and somehow make it to open new window not in WebBrowser control but in default browser?
msmuser  Sunday, September 10, 2006 4:40 PM

could be possible - in the webbrowser class/control take a look at the document property and its property (body, outer/inner html/text etc....)

ahmedilyas  Sunday, September 10, 2006 4:44 PM

Hi msmuser, I dont really understand what u want to achieve but here is one way of doing it if u dont need to open any browser, just send your data via POST method.


// Using WebRequest to send data to a website
WebRequest request = WebRequest.Create("http://blabla.com/answer.aspx");

//Set method property
request.Method = "POST";
//Create POST data
string postData = "myfirstdata=" + TextBox1.Text + "&myseconddata=" + TextBox2.Text;
//and convert it to byte array
byte[] dataBuffer = System.Text.Encoding.UTF8.GetBytes(postData);
//Set ContentType property of the request
request.ContentType = "application/x-www-form-urlencoded";
//Set ContentLength property of the request
request.ContentLength = dataBuffer.Length

//Get request stream
Stream postStream = request.GetRequestStream();
//Write data to request stream
postStream.Write(dataBuffer, 0, dataBuffer.Length);
//Close stream object
postStream.Close();

And then if u need to get response, just use WebResponse class and make use of the response stream.

Hope this helps.

Shah

shahrul  Monday, September 11, 2006 6:30 AM
I used WebClient instead.It seems to be just for those kinds of tasks.
Now the problem is the page is giving me response "Not signed in...".And page is using cookies for authentication.
Thats the reason I tried to call Browser so I would already be authenticated.

I discovered CookieContainer class but WebClient doesnt seem to have that.So do I need to switch to HttpWebRequest instead?
msmuser  Tuesday, September 12, 2006 4:29 PM

Try using this method:

HttpWebRequest myReq = WebRequest.Create(http://you_web_address);
myReq.CookieContainer = new CookieContainer();
myReq.CookieContainer.Add(new Cookie("name", "value"));
HttpWebResponse myRes = (HttpWebResponse)myReq.GetResponse();
string response = "";
Stream stream = myRes.GetResponseStream();
StreamReader reader = new StreamReader(stream, System.Text.Encoding.GetEncoding("utf-8"));
response = reader.ReadToEnd();
stream.Close; reader.Close(); myRes.Close();
webBrowser1.DocumentText = response;

of course you will need a web browser control in your form

CSharpFreak  Tuesday, September 12, 2006 5:54 PM
Well I found code on the web how to extend WebClient to accept cookies.

public class WebClientExtended : WebClient
{
private CookieContainer myContainer;
private HttpWebRequest myRequest;
private string myMethod;

public string Method
{
get { return myMethod; }
set { myMethod = value; }
}

public CookieContainer Cookies
{
get
{
if (myContainer == null)
{
myContainer = new CookieContainer();
}
return myContainer;
}
set
{
myContainer = value;
}
}

protected override WebRequest GetWebRequest(Uri address)
{
myRequest = (HttpWebRequest)base.GetWebRequest(address);
myRequest.Method = this.Method;
myRequest.CookieContainer = Cookies;
return myRequest;
}

protected override WebResponse GetWebResponse(WebRequest request)
{
return myRequest.GetResponse();
}

protected override WebResponse GetWebResponse(WebRequest request, IAsyncResult result)
{
return myRequest.EndGetResponse(result);
}


msmuser  Tuesday, September 12, 2006 11:22 PM
Dim url As String = ("http://localhost:1080/Test/")
Dim postdata As String = "username=myname"
Dim request As HttpWebRequest = CType(WebRequest.Create(url), HttpWebRequest)
Dim page As String
Try
Dim postsourcedata As String = postdata
request.KeepAlive = False
request.ProtocolVersion = HttpVersion.Version10
request.Method = "POST"
request.ContentType = "application/x-www-form-urlencoded"
request.ContentLength = postsourcedata.Length
request.AllowAutoRedirect = True
request.MaximumAutomaticRedirections = 10
request.Timeout = CType((New TimeSpan(0, 0, 60)).TotalMilliseconds, Integer)
request.UserAgent = "Mozilla/3.0 (compatible; My Browser/1.0)"
Dim writeStream As Stream = request.GetRequestStream
Dim bytes As Byte() = System.Text.Encoding.ASCII.GetBytes(postsourcedata)
writeStream.Write(bytes, 0, bytes.Length)
writeStream.Close()
Dim response As HttpWebResponse = CType(request.GetResponse, HttpWebResponse)
Dim responseStream As Stream = response.GetResponseStream
Dim readStream As StreamReader = New StreamReader(responseStream, Encoding.UTF8)
page = readStream.ReadToEnd

Catch ee As Exception
page = "fail!" & ee.Message
Finally

End Try
MsgBox(page)

---------------------------------------------------------------------------
when I am executing this code I am getting error like
1: The remote server returned an error: (405) Method Not Allowed.
OR
2:The underlying connection was closed: An unexpected error occurred on a receive.
EmersioN  Friday, January 19, 2007 1:56 PM

Hi

You can use XMLHTTP Object as follows

just add reference of  the msxml6.dll

''' <summary>

''' HttpPost Contains static functions to send/post data to

''' webservice of studio application.

''' </summary>

Public Class HttpPost

 

    ''' <summary>

    ''' Posts data to webservies of StudioApp

    ''' and gets the response from webservice

    ''' </summary>

    ''' <param name="DATA_TO_POST">data that you want to post</param>

    ''' <returns>response text send by webservies</returns>

    Shared Function PostData(ByRef DATA_TO_POST As String) As String

        Dim http As New MSXML2.XMLHTTP()

        ModPreference.WEBSERVICE_URL.Preferense = "http://localhost/Test/Default.aspx"

        http.open("POST", ModPreference.WEBSERVICE_URL.Preferense, False)

        http.setRequestHeader("content-type", "application/x-www-form-urlencoded")

        http.send(DATA_TO_POST)

        Return http.responseText

    End Function

 

    Shared Function PostData(ByVal Url As String, ByRef DATA_TO_POST As String) As String

        Dim http As New MSXML2.XMLHTTP()

        http.open("POST", Url, False)

        http.setRequestHeader("content-type", "application/x-www-form-urlencoded")

        http.send(DATA_TO_POST)

        Return http.responseText

    End Function

 

 

End Class

 

you can access posted data using Request.Params()

 

EmersioN  Wednesday, January 24, 2007 8:39 AM

You can use google to search for other answers

Custom Search

More Threads

• Strange Location Behaviour
• source control in drag and drop
• My message filter is a sieve!
• scroll and focus bug
• Call function on Parent form
• bitmap clarity +C#
• Encrypt Configuration Block Settings?
• OnPaint is called for each child?
• Mail Attachment
• compilation error while using AppReader