http请求c#授权



我目前正试图通过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." +
                                "nnException 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-未授权访问资源

我做错了什么?

授权头的一个例子是.

授权:基本QWxhZGRpbjpvcGVuIHNlc2FtZQ==

我很想看看你的代币价值。

相关内容

  • 没有找到相关文章

最新更新