到底是学艺不精哈。最近有点流年不利。总是遇到莫名其妙的坑。https发送post请求,死活返回的都是500(内部服务器错误)。郁闷ing。代码调试也没有提示啥有效的错误提示。用抓包工具也看不出任何异常。只有postman能调通,postman是何方神圣?为啥总能调通。期初还以为是证书之类的问题,在代码中添加了证书之类的东西也还是不行,依然不能解决问题。在google上查了半天,没有一个人遇到过我的问题么?郁闷ing.最后死马当成活马医,在代码中加了这么一段:
request.Credentials = CredentialCache.DefaultCredentials;
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
我现在依然是懵逼的状态。好歹问题是解决了。现在还不知道原理是啥。最近有点忙,留待日后再来理会,或者哪位高人看到,帮我指点一二,在此,不胜感激。哈哈。以下是完整的代码,仅供参考。哈哈。
public static string Post(string strUrl, string strParam)
{
ServicePointManager.DefaultConnectionLimit = 100;
ServicePointManager.Expect100Continue = false;
Stream myResponseStream = null;
StreamReader myStreamReader = null;
HttpWebRequest request = null;
HttpWebResponse response = null;
try
{
string strURL = strUrl;
request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
request.Credentials = CredentialCache.DefaultCredentials;
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout = 10000;
string paraUrlCoded = strParam;
byte[] payload;
payload = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(paraUrlCoded);
request.ContentLength = payload.Length;
myResponseStream = request.GetRequestStream();
myResponseStream.Write(payload, 0, payload.Length);
myResponseStream.Close();
response = (System.Net.HttpWebResponse)request.GetResponse();
System.IO.Stream s;
s = response.GetResponseStream();
string StrDate = "";
string strValue = "";
myStreamReader = new StreamReader(s, Encoding.GetEncoding("UTF-8"));
while ((StrDate = myStreamReader.ReadLine()) != null)
{
strValue += StrDate + "\r\n";
}
return strValue;
}
catch (Exception ex)
{
Console.WriteLine("getUrl = " + strUrl + " Exception" + ex);
//LogHelper.CreateErrorLogTxt("PostJson", ex.Source.ToString(), ex.Message);
}
finally
{
if (myStreamReader != null)
{
myStreamReader.Close();
}
if (myResponseStream != null)
{
myResponseStream.Close();
}
if (response != null)
{
response.Close();
}
if (request != null)
{
request.Abort();
}
}
return "{\"soundCode\":\"1419\",\"code\":\"1\",\"message\":\"网络连接异常\"}";
}
}