1、HttpWebRequest加入headers用户名称和密码方法;
private string doPost(string postUrl, string data, Encoding dataEncode, string username, string password)
{
string responseContent = string.Empty;
try
{
//dataEncode = Encoding.GetEncoding("GB2312");
byte[] byteArray = dataEncode.GetBytes(data); //转化
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
webReq.Method = "POST";
webReq.ContentType = "application/json";
//webReq.KeepAlive = false;
//webReq.ProtocolVersion = HttpVersion.Version10;
// webReq.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
//System.Net.ServicePointManager.DefaultConnectionLimit = 50;
ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;
if (!string.IsNullOrEmpty(username))
{
// (1)设置请求Credentials
CredentialCache credentialCache = new CredentialCache();
credentialCache.Add(new Uri(baseUrl), "Basic", new NetworkCredential(username, password));
webReq.Credentials = credentialCache;
// (2)设置Headers Authorization
string usernamePassword = username + ":" + password;
webReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(usernamePassword)));
}
webReq.ContentLength = byteArray.Length;
using (Stream reqStream = webReq.GetRequestStream())
{
reqStream.Write(byteArray, 0, byteArray.Length);//写入参数
//reqStream.Close();
}
using (HttpWebResponse response = (HttpWebResponse)webReq.GetResponse())
{
//在这里对接收到的页面内容进行处理
using (StreamReader sr = new StreamReader(response.GetResponseStream(), dataEncode))
{
responseContent = sr.ReadToEnd().ToString();
}
}
}
catch (System.Net.WebException ex)
{
//响应流
var mResponse = ex.Response as HttpWebResponse;
if (mResponse != null)
{
var responseStream = mResponse.GetResponseStream();
if (responseStream != null)
{
var streamReader = new StreamReader(responseStream, dataEncode);
//获取返回的信息
responseContent = streamReader.ReadToEnd();
streamReader.Close();
responseStream.Close();
}
}
responseContent = "获取数据失败,请重试!" + postUrl + ex.ToString() + " 返回数据" + responseContent;
}
return responseContent;
}
2、 基础连接已经关闭: 发送时发生错误
执行时有可能报这个这个错误信息,查原因;
原因:使用。net版本是2。0
加入 ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;
成功解决问题