访问请求/响应标头C#

时间:2018-05-28 14:58:31

标签: c# http networking

我目前正在尝试使用C#访问请求/响应标头,以及从具有用户名/密码登录名的网站访问请求/响应正文。我相信我已经到了登录的目的,它主要是访问数据。

首先,我打开HttpWebRequest到登录页面并提交我的凭据。然后我创建一个带有代理的webclient来登录远程服务器并为其提供凭据。然后我尝试下载数据,但我得到的只是响应体,但我需要请求体和服务器请求头

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using System.Web;
using System.Collections.Specialized;
using System.Runtime.InteropServices;
using System.Data.OleDb;
namespace ScrapeTest
 {
    class Program{

        static void Main(string[] args){
            HttpWebRequest baseRequest = WebRequest.Create("remoteserver") as HttpWebRequest;
            baseRequest.Timeout = 50000;
            baseRequest.MaximumAutomaticRedirections = 7;
            baseRequest.Credentials = new NetworkCredential("username", "password");
            HttpWebResponse baseResponse = baseRequest.GetResponse() as HttpWebResponse;
            WebClient client = new WebClient();
            WebProxy proxy = new WebProxy("proxyServer",true);
            proxy.Credentials = new NetworkCredential("proxyUsername", "proxyPassword");
            proxy.UseDefaultCredentials = true;
            WebRequest.DefaultWebProxy = proxy;
            client.Proxy = proxy;
            string head = client.Headers.ToString();
            NameValueCollection data = new NameValueCollection();
            byte[] res = client.UploadValues("otherPage", "GET", data);
            string resString = System.Text.Encoding.UTF8.GetString(res);
            Console.WriteLine(resString);
            byte[] info = client.DownloadData("otherPage");
            string responseString = System.Text.Encoding.UTF8.GetString(info);
            Console.WriteLine(responseString);
            client.Dispose();
            baseResponse.Close();
            Console.ReadLine();
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

如果你在C#中创建一个表单,我认为,或者如果使用ASP.NET可能会更容易。

以下是另一个关于如何访问表单数据的简单示例:

NameValueCollection nvc = Request.Form;
string userName, password;
if (!string.IsNullOrEmpty(nvc["txtUserName"]))
{
  userName = nvc["txtUserName"];
}

if (!string.IsNullOrEmpty(nvc["txtPassword"]))
{
  password = nvc["txtPassword"];
}

以下是Microsoft提供的有关Form类的更多信息:https://msdn.microsoft.com/en-us/library/system.web.httprequest.form(v=vs.110).aspx

但是,如果您提供更多详细信息,我们可以为您提供更好的答案。