所以我认为是时候学习 C# 了,对我来说放轻松,我对此很陌生。
我正在尝试创建一个非常简单的应用程序(我正在使用 Windows 窗体应用程序)。 我的目标是:
- 使用“GET”方法,获取网页
- 读取一个文本字段(每次用户访问页面时这个值都会改变
- 使用“POST”方法,相应地发送一些值
到目前为止,这是我的代码:
private void button2_Click(object sender, EventArgs e)
{
string URI = "http://localhost/post.php";
string myParameters = "field=value1&field2=value2";
using (WebClient wc = new WebClient())
{
string getpage = wc.DownloadString("http://localhost/post.php");
MessageBox.Show(getpage);
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string HtmlResult = wc.UploadString(URI, myParameters);
MessageBox.Show(HtmlResult);
}
}
到目前为止一切顺利,它正在运行,但这并不完全是我想要在这里实现的目标。 我可以使用 POST 方法,但如何在发送数据之前使用 GET? 我想根据GET结果发送数据。
如果我应该对我正在尝试做的事情进行更好的描述,请告诉我。
谢谢。
编辑
这是我的 PHP 代码:
<?php
$a = session_id();
if(empty($a))
session_start();
echo "Session: ".session_id()."<br/>\n";
现在,回到我的 C# 代码,我在两条消息中得到了不同的 session ID
最佳答案
使用 GET 读取数据
Please refer to this answer: Easiest way to read from a URL into a string in .NET
using(WebClient client = new WebClient()) {
string s = client.DownloadString(url);
}
session
默认情况下 WebClient 不使用任何 Session。因此,每个调用都被处理,就好像您创建了一个新 session 一样。为此,您需要这样的东西:
Please refer to these answers:
示例代码
public class CookieAwareWebClient : WebClient
{
private readonly CookieContainer m_container = new CookieContainer();
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
HttpWebRequest webRequest = request as HttpWebRequest;
if (webRequest != null)
{
webRequest.CookieContainer = m_container;
}
return request;
}
}
// ...
private void button2_Click(object sender, EventArgs e)
{
string URI = "http://localhost/post.php";
string myParameters = "field=value1&field2=value2";
using (WebClient wc = new CookieAwareWebClient())
{
string getpage = wc.DownloadString("http://localhost/post.php");
MessageBox.Show(getpage);
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string HtmlResult = wc.UploadString(URI, myParameters);
MessageBox.Show(HtmlResult);
}
}
关于C# WebRequest 获取/发布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26308167/