Add Custom Headers using HttpWebRequest

2020-02-09 07:38发布

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

HTTP Header

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");

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);

3条回答
Luminary・发光体
2楼-- · 2020-02-09 08:38

A simple method of creating the service, adding headers and reading the JSON response,

private static void WebRequest()
{
    const string WEBSERVICE_URL = "<<Web Service URL>>";
    try
    {
        var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
        if (webRequest != null)
        {
            webRequest.Method = "GET";
            webRequest.Timeout = 20000;
            webRequest.ContentType = "application/json";
            webRequest.Headers.Add("Authorization", "Basic dcmGV25hZFzc3VudDM6cGzdCdvQ=");
            using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
            {
                using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
                {
                    var jsonResponse = sr.ReadToEnd();
                    Console.WriteLine(String.Format("Response: {0}", jsonResponse));
                }
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}
查看更多
冷血范
3楼-- · 2020-02-09 08:43

IMHO it is considered as malformed header data.

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

The second way is true.

查看更多
不美不萌又怎样
4楼-- · 2020-02-09 08:45

You should do ex.StackTrace instead of ex.ToString()

查看更多
登录 后发表回答