C # calls the WebService that require a certificate via the HTTP POST method

Source: Internet
Author: User
Tags add time http post

A period of time to do Citibank's project, the use of Citi's interface is Websevice, for many reasons directly in the project reference webservice unsuccessful, so the HTTP POST request, the request information (XML format) is assembled and sent to the server, return results.

I would like to share the way I did at the time, hope to be useful to everyone.

1, first configure the required information in the Webconfig

Note: The Rewardurl is the common part of the URL address, because the address is different after the call to various interfaces, so it is drawn out separately defined, Commonurl for the ip+ port number, because this address can be replaced so also defined separately.
<appSettings>    <AddKey= "Cerpath"value= "E:\\avantouch.pfx" />    <AddKey= "Commonurl"value= "https://192.168.1.1:15121"/>    <AddKey= "Rewardurl"value= "/svcimpl/cards/reward/"/>  </appSettings>

2, define global variables, get the values in Webconfig, and the variables to be used later

Private Static ReadOnly stringCommonurl = configurationmanager.appsettings["Commonurl"].   ToString (); Private Static ReadOnly stringRewardurl = configurationmanager.appsettings["Rewardurl"].   ToString (); Private Static ReadOnly stringCerpath = configurationmanager.appsettings["Cerpath"].   ToString (); stringPostURL ="";

3, write public methods, this method of my son Ah project in a number of places to use, seemingly very redundant, can be integrated into the following methods, but in my project need this will be more convenient, so I do not integrate, we can according to their needs to integrate.

        /// <summary>        ///Get the results (this method is primarily to get posturl and then call the following method)/// </summary>        /// <param name= "xml" ></param>        /// <param name= "InterfaceName" >the caller interface method name that needs to be called</param>        /// <returns></returns>        Private stringGetrescode (stringXmlstringInterfaceName) {PostURL= Rewardurl + InterfaceName;//IP and address after port number            byte[] data =Encoding.UTF8.GetBytes (XML.            ToString ()); stringRescode = getpostrequest (data, posturl);//method is belowLog.info ("Response:"+Rescode); returnRescode; }

4, write the third part of the code used in the method, this is more important.

/// <summary>        ///Post method request get return value/// </summary>        /// <param name= "Data" ></param>        /// <returns></returns>        Private stringGetpostrequest (byte[] Data,stringURL) {            Try            {HttpWebRequest myrequest= (HttpWebRequest) webrequest.create (Commonurl +URL);//Full Request Address (IP: port number/+url)

X509 Certificate
                New the certificate Password " , X509keystorageflags.machinekeyset);                 = System.Security.Principal.TokenImpersonationLevel.Impersonation;                 // set a validation callback (always agree )
Servicepointmanager.servercertificatevalidationcallback =NewRemotecertificatevalidationcallback (CheckValidationResult);
Myrequest.method ="POST"; Myrequest.contenttype="text/xml;charset=\ "Utf-8\""; Myrequest.accept="Text/xml"; MYREQUEST.HEADERS.ADD ("SOAPAction", URL);//I do the process, this step did not add time has been wrong, plus this is OK. //whether to send with the requestMyrequest.usedefaultcredentials =true; Myrequest.contentlength=data. Length; MYREQUEST.CLIENTCERTIFICATES.ADD (cert);//Add the certificate into the HTTP request Stream Newstream=Myrequest.getrequeststream (); //Send the data.Newstream.write (data,0, data. Length); Newstream.close (); //Get Response varResponse =(HttpWebResponse) myrequest.getresponse (); using(varReader =NewStreamReader (response. GetResponseStream (), Encoding.GetEncoding ("UTF-8"))) { stringresult =Reader. ReadToEnd (); Reader. Close (); Response. Close (); returnresult; } } Catch(Exception ex) {log.info (ex); returnEx. ToString (); } }
Callback Method Public Static BOOLCheckValidationResult (Objectsender, X509Certificate certificate, X509chain chain, sslpolicyerrors errors) { //Always accept return true; }

5, the method is finished, just send your XML to the past, and the name of the interface you want to invoke pass through, call the third step method, for example:

Getrescode (XML, "Login"), so return the information, I do the project returns XML format information, parse the XML can get the results you want.

conclusion, there is a summary of the wrong place please help to point out, but also hope that your study work useful. My e-mail: [Email protected]

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.