我目前正尝试使用此代码通过https发布请求
const string url = "http://api.xxx.pt/";
const string username = "username";
const string password = "password";
const string token = "token";
const string json = "{jsondata}";
try
{
// Create a request using a URL that can receive a post.
WebRequest request2 = WebRequest.Create(url);
request2.Headers["Authorization"] = token;
// Set the Method property of the request to POST.
request2.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = json;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request2.ContentType = "application/json";
// Set the ContentLength property of the WebRequest.
request2.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request2.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response2 = request2.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response2).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response2.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response2.Close();
}
catch (WebException e)
{
Console.WriteLine("This program is expected to throw WebException on successful run." +
"\n\nException Message :" + e.Message);
if (e.Status == WebExceptionStatus.ProtocolError)
{
Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
此代码在MSDN库中无需身份验证即可正常运行 一旦我做了一些更改,添加一些身份验证
这一行
WebResponse response2 = request2.GetResponse();
回复401 - 取消授权访问资源
我做错了什么?
答案 0 :(得分:0)
授权标题的一个例子是。
授权:基本QWxhZGRpbjpvcGVuIHNlc2FtZQ ==
我很想看到你的代币值。