
static void Main(string[] args)
{
strUserName = "test";
strPassWord = "test";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, error) =>
{
return true;
};
string getJson = string.Empty;
string url = "https://10.0.18.41:8081/api/v1/oauth/token";
string postdata = "grant_type=password&username=" + strUserName + "&password=" + strPassWord;
getJson = PostUrl(url, postdata);
Console.WriteLine(getJson);
Console.ReadKey();
}
static string PostUrl(string strUrl, string strPostData)
{
string strReturnValue = string.Empty;
try
{
HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(strUrl);
httpReq.Method = "POST";
httpReq.Timeout = 100000;//设置请求超时时间,单位为毫秒
httpReq.KeepAlive = false;
httpReq.ProtocolVersion = HttpVersion.Version10;
httpReq.ContentType = "application/x-www-form-urlencoded";
if (strUserName != string.Empty || strPassWord != string.Empty)
{
string usernamePassword = strUserName + ":" + strPassWord;
usernamePassword = "test1:test1";
httpReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(usernamePassword)));
}
byte[] bytePostData = Encoding.UTF8.GetBytes(strPostData);
httpReq.ContentLength = bytePostData.Length;
using (Stream reqStream = httpReq.GetRequestStream())
{
reqStream.Write(bytePostData, 0, bytePostData.Length);
reqStream.Close();
}
HttpWebResponse httpResponse = (HttpWebResponse)httpReq.GetResponse();
Stream stream = httpResponse.GetResponseStream();
//获取响应内容
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
strReturnValue = reader.ReadToEnd();
reader.Close();
}
if (httpResponse != null)
{
httpResponse.Close();
}
if (httpReq != null)
{
httpReq.Abort();
}
}
catch(Exception ex)
{
AppLogHelper.WriteErrorLog(ex);
}
return strReturnValue;
}