C # use http post to call the webservice that requires a certificate

Source: Internet
Author: User

C # use http post to call the webservice that requires a certificate
I used the Citi interface websevice for the Citibank project some time ago. For many reasons, it was unsuccessful to directly reference webservice in the project, so I used the http post request, after the request information (in xml format) is assembled, it is sent to the server and the result is returned. I will share with you the method I made at the time and hope it will be useful to you. 1. First, configure the required information in webconfig. Note: RewardUrl is the public part of the url address. Because different interfaces are called later, the addresses are different, therefore, the CommonUrl is defined separately because the address may be changed. <Deleetask> <add key = "CerPath" value = "E: \ avantouch. pfx "/> <add key =" CommonUrl "value =" https: // 192.168.1.1: 15121 "/> <add key =" RewardUrl "value ="/SvcImpl/cards/reward/"/> </appSettings> 2. Define global variables and obtain values in webconfig, and the variable private static readonly string CommonUrl = ConfigurationManager. deleetask[ "CommonUrl"]. toString (); private static readonly string RewardUrl = ConfigurationManager. appSettings ["R EwardUrl "]. toString (); private static readonly string CerPath = ConfigurationManager. appSettings ["CerPath"]. toString (); string PostUrl = ""; 3. Write a public method. This method is used in many places in the project. It seems to be a lot more, it can be integrated into the following method, but it is more convenient to use this method in my project, so I have not integrated it. You can integrate it as needed. Copy the code /// <summary> /// obtain the result (this method is mainly used to obtain the PostUrl and then call the following method) /// </summary> /// <param name = "xml"> </param> /// <param name = "interfaceName"> name of the method to be called </param> // <returns> </returns> private string GetResCode (string xml, string interfaceName) {PostUrl = RewardUrl + interfaceName; // the ip address and the address byte [] data = Encoding after the port number. UTF8.GetBytes (xml. toString (); string resCode = GetPostRequest (data, PostUrl); // The method is as follows: Log. Info ("Response:" + resCode); return resCode;} copy code 4 and write the methods used by the code in the third part. This is important. Copy the code /// <summary> /// Post request to obtain the returned value // </summary> /// <param name = "data"> </param> // /<returns> </returns> private string GetPostRequest (byte [] data, string url) {try {HttpWebRequest myRequest = (HttpWebRequest) WebRequest. create (CommonUrl + url); // complete request address (ip: Port Number/+ url) // X509 Certificate X509Certificate2 cert = new System. security. cryptography. x509Certificates. x509Certificate2 (CerPath, "certificate password", X509KeyStora GeFlags. machineKeySet); myRequest. impersonationLevel = System. security. principal. tokenImpersonationLevel. impersonation; // set the verification callback (always agree) ServicePointManager. serverCertificateValidationCallback = new RemoteCertificateValidationCallback (CheckValidationResult); myRequest. method = "POST"; myRequest. contentType = "text/xml; charset = \" UTF-8 \ ""; myRequest. accept = "text/xml"; myRequest. headers. add ("SOAPActi On ", url); // an error occurs when this step is not added. If this step is added, it is OK. // Whether to send myRequest together with the request. usedefacrecredentials = true; myRequest. contentLength = data. length; myRequest. clientCertificates. add (cert); // Add the certificate to the http request Stream newStream = myRequest. getRequestStream (); // Send the data. newStream. write (data, 0, data. length); newStream. close (); // Get response var response = (HttpWebResponse) myRequest. getResponse (); using (var reader = new StreamReader (response. getResponse Stream (), Encoding. getEncoding ("UTF-8") {string result = reader. readToEnd (); reader. close (); response. close (); return result ;}} catch (Exception ex) {Log. info (ex); return ex. toString () ;}}// callback method public static bool CheckValidationResult (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) {// always accept return true;} copy Code 5, after the method is completed, you only need to pass your xml message and the interface name you want to call to pass it to step 3. For example, GetResCode (xml, "Login"). In this way, information is returned. The information in xml format is returned for my project, parse xml to get the desired result.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.