【发布时间】:2020-03-09 00:25:34
【问题描述】:
我有一个返回令牌的 API。使用邮递员,我可以通过在标题部分设置授权来获取令牌详细信息。根据 API 规范,我将单选按钮选择为 application/x-www-form-urlencoded,并在邮递员正文中将键值设置为 grant_type,并将值设置为 client_credentials。
当我尝试在 c# 中实现相同的目标时,我无法弄清楚如何将键值 grant_type 和值设置为 client_credentials。
下面是我的代码,当我运行代码时出现错误。任何人都可以帮助我在WebRequest 中将grant_type 设置为键和值client_credentials。我还附上了屏幕截图。
the underlying connection was closed an unexpected error occurred on send
以下是捕获的内部异常。 {"Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host."}
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
//request.ContentLength = 0; // new commented
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
string postData = "grant_type=client_credentials"; // Not sure if we can set the values like this
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] bytes = encoding.GetBytes(postData);
request.Headers.Add("Authorization", ConfigurationManager.AppSettings.Get("TokenAuthorizationKey").ToString());
request.Timeout = 600000;
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = bytes.Length;
request.KeepAlive = true;
Stream newStream = request.GetRequestStream(); // this Line throws Error
newStream.Write(bytes, 0, bytes.Length);
using (var response = (HttpWebResponse)request.GetResponse())
{
var responseValue = string.Empty;
if (response.StatusCode != HttpStatusCode.OK)
{
var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
throw new ApplicationException(message);
}
using (var responseStream = response.GetResponseStream())
{
if (responseStream != null)
using (var reader = new StreamReader(responseStream))
{
responseValue = reader.ReadToEnd();
}
}
return responseValue;
}
【问题讨论】:
标签: c# rest postman access-token webrequest