我不确定这些突出显示的值是什么类型的标头,但我应该如何使用HttpWebRequest添加它们?
突出显示的部分是否被视为http请求或标题数据的正文?换句话说,哪种方式是正确的?
以下是我目前使用的代码:
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请求吗?
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);
答案 0 :(得分:15)
创建服务,添加标头和阅读JSON响应的简单方法
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());
}
}
答案 1 :(得分:13)
恕我直言,它被视为格式错误的标题数据。
您确实希望将这些名称值对作为请求内容发送(这是POST的工作方式)而不是标题。
第二种方式是真的。
答案 2 :(得分:-1)
您应该执行 ex.StackTrace ,而不是 ex.ToString()