C# HTTPS request with post

本文关键字:post with request HTTPS | 更新日期: 2023-09-27 17:52:35

我希望为HTTPS提供一个完整的示例答案HTTP请求post特别是方法3。特别是包括上下文中使用的安全策略。既适用于没有证书的情况也适用于有证书的情况。在我的示例中,我没有真正的证书,但必须使用HTTPS。我想知道我是否又犯了一个初学者犯的错误。代码如下(链接更改为冒牌)我从这里开始执行HTTP的步骤:https://msdn.microsoft.com/en-us/library/debx8sh9%28v=vs.110%29.aspx

关于HTTPS帖子的其他答案,无论是在StackOverFlow中还是在外部,要么指向一个过时的安全类,要么只是部分例子。我想其他初学者也会参考一个更最新的答案和完整的例子。

这里的c#代码返回500,但我需要确信我的安全策略调用不是原因。
谢谢你的帮助

using System;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Text;
using System.Security.Cryptography.X509Certificates;
namespace GradeSync
{

/* HTTP POST
The following is a sample HTTP POST request and response. The placeholders shown need to be replaced with actual values.
REQUEST:
POST /webservices/PspServices.asmx/UpdateGradingSheet HTTP/1.1
Host: itech.psp.org
Content-Type: application/x-www-form-urlencoded
Content-Length: length
UserId=string&LessonId=string&Marks=string&ClassId=string
RESPONSE: 
HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: length
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">string</string>
 */

    public class PostGradesViaWebRequestPost
    {
        // https://stackoverflow.com/questions/5648596/call-webservice-from-c-sharp-application-using-ssl

        /// public bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        ///{
        ///    Console.WriteLine(sslPolicyErrors);  // Or whatever you want to do...
        ///    return true;
        ///}
        public static void Main()
        {
        string gradesURI = 
        "https://itech.psp.org/webservices/PspServices.asmx/UpdateGradingSheet";
        string userId  = "300810060";   // 300810060 = Dorinda Bex ; 300835525 = Rachel Bess
        string lesson  = "L1";          // Lesson #
        string points  =  "9";          // Review score
        string classId = "432462";     // 432462 = Independent Study 2014 - Sec.2 ; 432525 = Modesto, CA Spring 2015
        // https://stackoverflow.com/questions/12506575/how-to-ignore-the-certificate-check-when-ssl
        System.Net.ServicePointManager.ServerCertificateValidationCallback +=
            delegate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate,
                    System.Security.Cryptography.X509Certificates.X509Chain chain,
                    System.Net.Security.SslPolicyErrors sslPolicyErrors)
            {
                return true; // **** Always accept
            };
        //// goes with policy System.Net.ServicePointManager.ServerCertificateValidationCallback = policy.ValidateServerCertificate;
        //https://msdn.microsoft.com/en-us/library/debx8sh9%28v=vs.110%29.aspx
        // 1  Create a request using a URL that can receive a post. 
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(gradesURI);  /// new
        //xxWebRequest rqst = HttpWebRequest.Create(gradesURI);
        //WebRequest request = WebRequest.Create( gradesURI );
        // 2
        request.Credentials = CredentialCache.DefaultCredentials;
        request.ProtocolVersion = HttpVersion.Version11;
        /// not needed?  ((HttpWebRequest)request).UserAgent = ".NET Framework Exa
        /// mple Client";
        // 3 Set the Method property of the request to POST.
        request.Method = "POST";
        // 4 Set the ContentLength property of the WebRequest.
        // Create POST data and convert it to a byte array.
        string postData = "Userid="+userId + "&Lesson=" + lesson + "&Marks="+points + "&ClassId="+classId;
        byte[] byteArray = Encoding.UTF8.GetBytes (postData);
        // 5 Set the ContentType property of the WebRequest.
        request.ContentType = "application/x-www-form-urlencoded";   // OK right type
        //  Set the ContentLength property of the WebRequest.
        request.ContentLength = byteArray.Length;
        // 6 Get the request stream.
        Stream dataStream = request.GetRequestStream ();
        // 7 Write the data to the request stream.
        dataStream.Write (byteArray, 0, byteArray.Length);
        // 8 Close the Stream object.
        dataStream.Close ();

        //  Response  /////////////////////////////////////////////
        // 9 Get the response.
        WebResponse response = request.GetResponse();
        // 10 Display the status
        Console.WriteLine (((HttpWebResponse)response).StatusDescription);
        // 11 Get the stream containing content returned by the server.
        dataStream = response.GetResponseStream ();   // from example
        // 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 ();
        // 12
        response.Close();

        }  // end main
    }  // end class
}  // end namespace

C# HTTPS request with post

因为https在服务器端,所以根本不需要策略或安全代码!所以我可以使用post

的HTTP请求方法3

我的问题是打字错误(Lesson不是LessonId),但作为REST初学者,我认为这是HTTPS和安全策略。

现在想知道什么时候需要安全证书?(可能是回答)但这个问题可能更好。初学者需要提示才能回答正确的问题。