zoukankan      html  css  js  c++  java
  • PHP&Java 调用C#的WCF

    步骤一:用C#声明WCF

       [ServiceContract]
        public interface IService1 {
            [OperationContract]
            void DoWork();
    
            [OperationContract]
            string GetData();
    
            [OperationContract]
            string GetData2(string msg);
    
            [OperationContract]
            string GetData3(Order order);
    
            [OperationContract]
            IList<Order> GetList();
        }
    
        public class Service1 : IService1 {
            public void DoWork() {
            }
            public string GetData() {
                return DateTime.Now.ToString("成功:" + "yyyy-MM-dd");
            }
            public string GetData2(string msg) {
                return DateTime.Now.ToString("成功:" + "yyyy-MM-dd 您输入的内容是:" + msg);
            }
            public string GetData3(Order order) {
                return string.Format("成功:{0},OrderId:{1},Qty:{2}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), order.OrderId, order.Qty);
            }
            public IList<Order> GetList() {
                IList<Order> orders = new List<Order>();
                orders.Add(new Order { OrderId = "A001", Qty = 10 });
                orders.Add(new Order { OrderId = "A002", Qty = 20 });
                orders.Add(new Order { OrderId = "A003", Qty = 30 });
                return orders;
            }
        }
    
        public class Order {
            public string OrderId { get; set; }
            public int Qty { get; set; }
        }

    步骤二:用PHP调用:

    1.PHT调用WCF无参数
    <?php
    $wcfURL = 'http://192.169.1.100:8090/FPosServer_xncs/r/Service1.svc?wsdl';
    $wcfClient = new SoapClient ( $wcfURL );
    $result1 = $wcfClient->GetData();
    print_r ( $result1 );
    ?>
    
    
    2.PHT调用WCF传递一个string参数
    <?php
    $wcfURL = 'http://192.169.1.100:8090/FPosServer_xncs/r/Service1.svc?wsdl';
    $wcfClient = new SoapClient ( $wcfURL );
    $args = array('msg' => '312');
    $result1 = $wcfClient->GetData2($args);
    print_r ( $result1 );
    ?>
    
    3.PHT调用WCF传递一个对象参数
    <?php
    $wcfURL = 'http://192.169.1.100:8090/FPosServer_xncs/r/Service1.svc?wsdl';
    $wcfClient = new SoapClient ( $wcfURL );
    $param = array('OrderId'=>'A001','Qty'=>'1');
    $result1=$wcfClient->GetData3(array('order'=>$param));
    print_r ( $result1 );
    ?>

    4.Java调用WCF

    注意:如果请求的body有中文,一定要加body.getBytes("UTF-8")

    public static void main(String[] args) {
            try {
    
                String method = "AddVip"; // AddVip
                String uri = "http://192.168.18.50:8899/Yinger/YingerService?wsdl";
                String body = "<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body><AddVip xmlns="http://tempuri.org/"><jsonData>{"Vip":"1820000000","VipFrom":"APP","Recommend":"887061217","ChannelId":"5010280001","Name":"小花","Phone":"182000000","Sex":"2","BirthDate":"1992-03-02","Address":"广东省广州市番禺区","Province":"广东省","City":"广州市","District":"番禺区","Email":"86566@qq.com","Level":"会员卡","Password":"8888888","MemberType":"会员"}</jsonData><appKey>test</appKey><appSecret>123456</appSecret></AddVip></s:Body></s:Envelope>";
                System.out.println(body);
    
                byte[] data = body.getBytes("UTF-8");
    
                URL url = new URL(uri);
    
                System.out.println(uri);
    
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setDoOutput(true); // 设置允许输出
                conn.setConnectTimeout(20 * 1000); // 设置超时时间为5秒
    
                conn.setReadTimeout(30 * 1000);
    
                // 设置请求方式
                conn.setRequestMethod("POST");
                // 设置请求体属性
                conn.setRequestProperty("Content-Type", "text/xml;charset=utf-8");
                conn.setRequestProperty("SOAPAction", "http://tempuri.org/IYingerService/" + method);
    
                // 发送请求的xml文件
                OutputStream outputStream = conn.getOutputStream();
                outputStream.write(data);
                outputStream.flush();
                outputStream.close();
    
                int code = conn.getResponseCode();
                System.out.println("code:" + code);
                if (code == 200) {
                    // 读取服务器返回的消息
                    InputStream in = conn.getInputStream();
                    StringBuffer sb = new StringBuffer();
                    byte[] buf = new byte[1024];
                    for (int n; (n = in.read(buf)) != -1;) {
                        sb.append(new String(buf, 0, n, "utf-8"));
                    }
                    in.close();
                    conn.disconnect();
                    System.out.println(sb.toString());
                }
            } catch (Exception e) {
                System.out.println(e.getMessage());
                e.printStackTrace();
            }
        }

    5.C#调用WCF,用windows身份认证,Clinent代码:

    //使用BasicHttpBinding绑定
                BasicHttpBinding myBinding = new BasicHttpBinding();
                //使用Transport安全模式
                myBinding.Security.Mode = BasicHttpSecurityMode.Transport;
                //客户端验证为None
                myBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
                //客户端验证为Basic
                //myBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
                //客户端验证为Ntlm
                //myBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
    
                //客户端Endpoint地址,指向服务端Endpoint的地址
                EndpointAddress ea = new
                    EndpointAddress("https://win2008/WcfIISHostService/Service1.svc/GetIdentity");
    
                GetIdentityClient gc = new GetIdentityClient(myBinding, ea);
    
                //客户端为Basic时,客户端提供用户名和密码
                //gc.ClientCredentials.UserName.UserName = "chnking";
                //gc.ClientCredentials.UserName.Password = "jjz666";
    
    
                //执行代理类Get方法
                string result = gc.Get(WindowsIdentity.GetCurrent().Name);

    6.HttpHelper调用WCF,用windows身份认证:

       byte[] bytes = Encoding.Default.GetBytes(UserNo + ":" + Password);

       string Auth=Convert.ToBase64String(bytes);

    string xml = "";
                HttpHelper http = new HttpHelper();
                HttpItem item = new HttpItem()
                {
                    URL = "http://pidev.XXXX.com:50000/XISOAPAdapter/MessageServlet?senderParty=&senderService=BC_F360&receiverParty=&receiverService=&interface=SI_DeliveryIn_Req&interfaceNamespace=urn:F3602SAP:DeliveryIn",//URL     必需项    
                    Method = "post",//URL     可选项 默认为Get   
                    IsToLower = false,//得到的HTML代码是否转成小写     可选项默认转小写   
                    Cookie = "",//字符串Cookie     可选项   
                    Referer = "",//来源URL     可选项   
                    Postdata = xml,//Post数据     可选项GET时不需要写   
                    Timeout = 100000,//连接超时时间     可选项默认为100000    
                    ReadWriteTimeout = 30000,//写入Post数据超时时间     可选项默认为30000   
                    UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)",//用户的浏览器类型,版本,操作系统     可选项有默认值   
                    ContentType = "text/html",//返回类型    可选项有默认值   
                    Allowautoredirect = false,//是否根据301跳转     可选项   
                };
               
                //Authorization: Basic RjM2MFBJOmYzNjBhZG1pbjY2
                item.Header.Add("Authorization", "Basic RjM2MFBJOmYzNjBhZG1pbjY2");  //此处为base64加密, 明文:F360PI:f360admin66
    
                //SOAPAction: "http://sap.com/xi/WebService/soap1.1"
                item.Header.Add("SOAPAction", "http://sap.com/xi/WebService/soap1.1");
    
                HttpResult result = http.GetHtml(item);
                string html = result.Html;

    7.RestSharp 使用HttpBasicAuthenticator 调用Shopify

     var client = new RestClient("https://developmentsandriver.myshopify.com/")
                {
                    Authenticator = new HttpBasicAuthenticator("8d654c3a8404fc954d6653b100acbxxx", "sss0836672c0c518764506bf2ed3fe82")
                };
    
                var request = new RestRequest()
                {
                    Method = Method.GET,
                    Resource = "admin/products.json",
                    RequestFormat = DataFormat.Json,
                };
                var result = client.Execute(request);
                var count = result.Content;
  • 相关阅读:
    Hystrix熔断原理
    FeignClient Hystrix超时重试降级
    Windows上Docker Toolbox修改镜像源
    Windows10家庭版安装docker
    Class类文件结构--访问标志
    MySQL常见的七种锁详细介绍()
    maven setting.xml 阿里云镜像 没有一句废话
    mysql 批量操作,已存在则修改,不存在则insert,同时判断空选择性写入字段
    hdu5730
    3月部分题目简要题解
  • 原文地址:https://www.cnblogs.com/ycdx2001/p/call-api.html
Copyright © 2011-2022 走看看