使用 HttpWebRequest 添加自定义标头

Add Custom Headers using HttpWebRequest(使用 HttpWebRequest 添加自定义标头)

本文介绍了使用 HttpWebRequest 添加自定义标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定这些突出显示的值是什么类型的标头,但是我应该如何使用 HttpWebRequest 添加它们?

I am not really sure what type of headers these highlighted values are, but how should I add them using HttpWebRequest?

突出显示的部分是否被视为 http 请求的主体或标头数据?也就是说,哪种方式是正确的?

Is the highlighted part considered body of the http request or header data? In other words, which way is correct?

这是我目前使用的代码:

Here is the code I am currently using:

HttpWebRequest request = (HttpWebRequest) WebRequest.Create("/securecontrol/reset/passwordreset");
request.Headers.Add("Authorization", "Basic asdadsasdas8586");
request.ContentType = "application/x-www-form-urlencoded";
request.Host = "www.xxxxxxxxxx.com";
request.Method = "POST";
request.Proxy = null;
request.Headers.Add("&command=requestnewpassword");
request.Headers.Add("&application=netconnect");

但是我应该改用以下来构建上面的 Http 请求吗?

But should I use the following instead to build the Http Request above?

string reqString = "&command=requestnewpassword&application=netconnect";
byte[] requestData = Encoding.UTF8.GetBytes(reqString);

HttpWebRequest request = (HttpWebRequest) WebRequest.Create("/securecontrol/reset/passwordreset");
request.Headers.Add("Authorization", "Basic ashAHasd87asdHasdas");
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = requestData.Length;
request.Proxy = null;
request.Host = "www.xxxxxxxxxx.com";
request.Method = "POST";

using (Stream st = request.GetRequestStream())
st.Write(requestData, 0, requestData.Length);

推荐答案

恕我直言,它被视为格式错误的标头数据.

IMHO it is considered as malformed header data.

您实际上希望将这些名称值对作为请求内容发送(这是 POST 的工作方式)而不是作为标头.

You actually want to send those name value pairs as the request content (this is the way POST works) and not as headers.

第二种方法是正确的.

这篇关于使用 HttpWebRequest 添加自定义标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:使用 HttpWebRequest 添加自定义标头

基础教程推荐