Http Basic认证的请求头
public static string HttpPost(string url, string body, string usernamePassword)
{
try
{
ServicePointManager.ServerCertificateValidationCallback = Callback;
Encoding encoding = Encoding.UTF8;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.Accept = "application/json, text/javascript, */*";
request.ContentType = "application/json; charset=utf-8";
string base64 = Convert.ToBase64String(Encoding.Default.GetBytes(usernamePassword));
request.Headers.Add("Authorization", "Basic " + base64);
byte[] buffer = encoding.GetBytes(body);
request.ContentLength = buffer.Length;
request.GetRequestStream().Write(buffer, 0, buffer.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding))
{
return reader.ReadToEnd();
}
}
catch (WebException ex)
{
Logger.WriteLog("ex:" + ex.ToString());
var res = (HttpWebResponse)ex.Response;
StringBuilder sb = new StringBuilder();
StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
sb.Append(sr.ReadToEnd());
string ssb = sb.ToString();
return ssb;
}
}
|