C# WebRequest 获取/发布

标签 c# webrequest

所以我认为是时候学习 C# 了,对我来说放轻松,我对此很陌生。

我正在尝试创建一个非常简单的应用程序(我正在使用 Windows 窗体应用程序)。 我的目标是:

  1. 使用“GET”方法,获取网页
  2. 读取一个文本字段(每次用户访问页面时这个值都会改变
  3. 使用“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:

  1. Using CookieContainer with WebClient class

  2. Reading Response From URL using HTTP WEB REQUEST

示例代码

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/

相关文章:

c# - context.Database.ExecuteSqlCommand - 错误代码 701 - Microsoft Azure

c# - 将通过 HTTP 上传到 ASP.NET 的文件进一步上传到 C# 中的 FTP 服务器

c# - WebRequest - .timeout 问题

c# - 使用 System.Net.WebRequest 时无法设置某些 HTTP header

c# - YouTube视频信息通过浏览器和WebRequest C#返回不同的结果

c# - 如何停止 System.Threading.Timer

c# - 使用子字符串提取 YouTube 视频的视频 ID

c# - 我自己的 OrderBy 函数

c# - 知道为什么这个 RavenDB 查询只返回 6 个结果吗?

c# - WebRequest.Create 和 WebRequest.CreateHttp 之间的区别