码迷,mamicode.com
首页 > Windows程序 > 详细

FindApi基本使用

时间:2014-08-29 13:01:17      阅读:419      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   os   使用   io   strong   

添加服务引用  http://developer.ebay.com/webservices/Finding/latest/FindingService.wsdl  

添加并引入:SLF.dll,eBay.Service

配置文件代码

<appSettings>
    <!-- eBay 开发人员应用程序ID-->
    <add key="AppID" value="Appid"/>
    <!-- eBay Finding service 正式版服务地址-->
    <add key="FindingServerAddress" value="http://svcs.ebay.com/services/search/FindingService/v1"/>
    <!-- eBay token for 用户令牌 -->
    <add key="EBayToken" value="USER TOKEN" />
    <!-- eBay Trading API 正式版地址 address-->
    <add key="TradingServerAddress" value="https://api.ebay.com/wsapi"/>
  </appSettings>

添加WCF引用

 

bubuko.com,布布扣

创建几个辅助类

ServiceConstants:创建一个详细的SOA服务

using System;

namespace eBay.Services.Common
{
    /// <summary>
    /// Readonly constants specific to eBay SOA Services
    /// </summary>
    public abstract class ServiceConstants
    {
        /**
         * Prefix used by all SOA headers.
         */
        public static readonly string SYS_PREFIX = "X-EBAY-SOA-";

        /**
         * Message protocol (SOAP, etc.).
         */
        public static readonly string MESSAGE_PROTOCOL = SYS_PREFIX + "MESSAGE-PROTOCOL";

        /**
         * Service operation name.
         */
        public static readonly string SERVICE_OPERATION_NAME = SYS_PREFIX + "OPERATION-NAME";

        /**
         * Service qname.
         */
        public static readonly string SERVICE_NAME = SYS_PREFIX + "SERVICE-NAME";

        /**
         * Global ID for this request/response.
         */
        public static readonly string GLOBAL_ID = SYS_PREFIX + "GLOBAL-ID";

        /**
         * Service version in which client (in requests) or server (in responses) is operating.
         */
        public static readonly string VERSION = SYS_PREFIX + "SERVICE-VERSION";
        
        /**
         * Security related SOA headers
         */
        public static readonly string AUTH_APPNAME = SYS_PREFIX + "SECURITY-APPNAME";
        
        /**
         * SOA name for SOAP 1.1 protocol processor.
         */
        public static readonly string MSG_PROTOCOL_SOAP_11 = "SOAP11";

        /**
         * SOA name for SOAP 1.2 protocol processor.
         */
        public static readonly string MSG_PROTOCOL_SOAP_12 = "SOAP12";

       /**
        * Service kit name for tracking purpose
        */
       public static readonly string SERVICE_KIT_NAME = "eBayServiceKit(DotNet)";
    
       /**
        * User agent http header value for tracking purpose
        */
       public static readonly string USER_AGENT_VALUE = SERVICE_KIT_NAME;

       public static readonly string HEADER_USER_AGENT = "User-Agent";


       /**
        * Names of supported services, for tracking
        */
       public static readonly string FINDING_SERVICE_NAME = "FindingAPI";
    }
}

MessageInspector:自定义消息监听对日志和http头进行设置

using Slf;
using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;

namespace ConsoleApplication1
{
    public class MessageInspector : IClientMessageInspector
    {
        #region IClientMessageInspector Members

        private ILogger logger = LoggerService.GetLogger();

        private ClientConfig config;
        private string serviceName;

        public MessageInspector(ClientConfig config, string serviceName)
        {
            this.config = config;
            this.serviceName = serviceName;
        }

        /// <summary>
        /// Called after response is received
        /// </summary>
        /// <param name="reply"></param>
        /// <param name="correlationState"></param>
        public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {

            if (this.config.HttpHeaderLoggingEnabled)
            {
                //logging http headers
                HttpResponseMessageProperty httpResponse = reply.Properties[HttpResponseMessageProperty.Name] as HttpResponseMessageProperty;
                if (httpResponse != null && httpResponse.Headers != null && httpResponse.Headers.Count > 0)
                {
                    string httpHeaderMessage = "---[HTTP Response Headers]---\r\n";
                    foreach (string headerName in httpResponse.Headers.AllKeys)
                    {
                        httpHeaderMessage += headerName + " : " + httpResponse.Headers[headerName] + "\r\n";

                    }
                    logger.Info(httpHeaderMessage);

                }
                else
                {
                    logger.Info("HTTP Response Headers is not available!");
                }
            }

            if (this.config.SoapMessageLoggingEnabled)
            {
                //logging soap message
                string soapMessage = "receiving soap request message ...\r\n" + reply.ToString();
                logger.Info(soapMessage);
            }

        }

        /// <summary>
        /// Called before request is sent
        /// </summary>
        /// <param name="request"></param>
        /// <param name="channel"></param>
        /// <returns></returns>
        public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, IClientChannel channel)
        {
            // Make a copy of the SOAP packet for viewing.
            MessageBuffer buffer = request.CreateBufferedCopy(Int32.MaxValue);
            System.ServiceModel.Channels.Message msgCopy = buffer.CreateMessage();

            request = buffer.CreateMessage();

            // Get the SOAP XML content.
            string strMessage = msgCopy.ToString();
            if (this.config.SoapMessageLoggingEnabled)
            {
                //logging soap message
                string soapMessage = "sending soap request message ...\r\n" + strMessage;
                logger.Info(soapMessage);
            }

            HttpRequestMessageProperty httpRequest;
            if (request.Properties.ContainsKey(HttpRequestMessageProperty.Name))
            {
                httpRequest = request.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
            }
            else
            {
                httpRequest = new HttpRequestMessageProperty();
                request.Properties.Add(HttpRequestMessageProperty.Name, httpRequest);
            }

            // Get the SOAP XML body content.
            System.Xml.XmlDictionaryReader xrdr = msgCopy.GetReaderAtBodyContents();
            // Get operation name for the root element
            string opName = xrdr.LocalName;
            // Remove [Request] suffix
            opName = opName.Replace("Request", "");

            // Set soa specific headers
            // Set operation name
            httpRequest.Headers.Add(ServiceConstants.SERVICE_OPERATION_NAME, opName);

            // Set service version
            string serviceVersion = this.config.ServiceVersion;
            if (serviceVersion != null && serviceVersion.Length > 0)
            {
                httpRequest.Headers.Add(ServiceConstants.VERSION, serviceVersion);
            }

            // Set global id
            string globalId = this.config.GlobalId;
            if (globalId != null && globalId.Length > 0)
            {
                httpRequest.Headers.Add(ServiceConstants.GLOBAL_ID, globalId);
            }

            // Set appId
            string applicationId = this.config.ApplicationId;
            if (applicationId != null && applicationId.Length > 0)
            {
                httpRequest.Headers.Add(ServiceConstants.AUTH_APPNAME, applicationId);
            }


            string uaValue = ServiceConstants.USER_AGENT_VALUE;
            if (serviceName != null && serviceName.Length > 0)
            {
                uaValue = uaValue + "-" + serviceName;
            }
            httpRequest.Headers.Add(ServiceConstants.HEADER_USER_AGENT, uaValue);

            // http compression is not supported in current implementation
            /*if (config.HttpCompressionEnabled)
            {
                httpRequest.Headers.Add("Accept-Encoding", "gzip");
            }*/

            if (this.config.HttpHeaderLoggingEnabled)
            {
                //logging http headers
                string httpHeaderMessage = "---[HTTP Request Headers]---\r\n";
                foreach (string headerName in httpRequest.Headers.AllKeys)
                {
                    httpHeaderMessage += headerName + " : " + httpRequest.Headers[headerName] + "\r\n";

                }
                logger.Info(httpHeaderMessage);
            }

            return null;

        }
        #endregion
    }
}

MessageBehavior:自定义端口行为

using System;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;

namespace ConsoleApplication1
{
    class MessageBehavior : IEndpointBehavior
    {
        #region IEndpointBehavior Members

        private ClientConfig clientConfig;
        private string serviceName;

        public MessageBehavior(ClientConfig config, string serviceName)
        {
            this.clientConfig = config;
            this.serviceName = serviceName;
        }

        public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
        {
        }

        /// <summary>
        /// Enable custom message inspector
        /// </summary>
        /// <param name="endpoint"></param>
        /// <param name="clientRuntime"></param>
        public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
        {
            MessageInspector inspector = new MessageInspector(this.clientConfig, serviceName);
            clientRuntime.MessageInspectors.Add(inspector);
        }

        public void ApplyDispatchBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher)
        {
            throw new Exception("Behavior not supported on the consumer side!");
        }

        public void Validate(ServiceEndpoint endpoint)
        {
        }

        #endregion
    }
}

FindingServiceClientFactory:创建客户端代理
using ConsoleApplication1.EbayFindingService;
namespace ConsoleApplication1
{
    /// <summary>
    /// 创建客户端代理
    /// </summary>
    public class FindingServiceClientFactory
    {
        public static FindingServicePortTypeClient getSerivceClient(ClientConfig config)
        {
            return (FindingServicePortTypeClient)ClientFactory.GetSerivceClient<FindingServicePortType>(config, typeof(FindingServicePortTypeClient), ServiceConstants.FINDING_SERVICE_NAME);
        }
    }
}

ClientFactory:一个普通的工厂类取得易趣网SOA服务客户端代理的实例

using System;
using System.ServiceModel;
namespace ConsoleApplication1
{
    /// <summary>
    /// 一个普通的工厂类取得易趣网SOA服务客户端代理的实例
    /// </summary>
    public class ClientFactory
    {
        /// <summary>
        /// 最大接收WCF客户端消息的大小
        /// </summary>
        private static readonly long MAX_RECEIVE_MESSAGE_SIZE = 2147483647;
        public static ClientBase<TServiceContract> GetSerivceClient<TServiceContract>(ClientConfig config, Type clientType, string serviceName)
            where TServiceContract : class
        {
            //http绑定设置
            BasicHttpBinding binding = new BasicHttpBinding();
            //http超时设置
            if (config.HttpTimeout > 0)
            {
                binding.OpenTimeout = TimeSpan.FromMilliseconds(config.HttpTimeout);
                binding.ReceiveTimeout = TimeSpan.FromMilliseconds(config.HttpTimeout);
            }
            //需要通过WCF支持目标响应消息
            binding.MaxReceivedMessageSize = MAX_RECEIVE_MESSAGE_SIZE;
            //支持HTTPs协议
            string endPointAddress = config.EndPointAddress;
            if (endPointAddress.StartsWith("https"))
            {
                binding.Security.Mode = BasicHttpSecurityMode.Transport;
            }
            //建立端口地址
            EndpointAddress address = new EndpointAddress(endPointAddress);
            //使用反射创建一个特定的客户实例
            ClientBase<TServiceContract> client = (ClientBase<TServiceContract>)Activator.CreateInstance(clientType, new object[] { binding, address });
            //添加客户行为的客户实例
            MessageBehavior behavior = new MessageBehavior(config, serviceName);
            client.Endpoint.Behaviors.Add(behavior);
            return client;
        }
    }
}

ClientConfig:配置ebay SOA服务客户端

namespace ConsoleApplication1
{
    /// <summary>
    /// 配置ebay SOA服务客户端
    /// </summary>
    public class ClientConfig
    {
        #region Fields
        private string applicationId;
        private string serviceVersion;
        private string globalId;

        private string endPointAddress;
        private bool httpCompressionEnabled = true;
        private bool httpHeaderLoggingEnabled = true;
        private int httpTimeout = 60000;
        private bool soapMessageLoggingEnabled = true;
        #endregion
        #region Properties

        /// <summary>
        /// eBay developer account application ID (AppID),
        /// this is mandatory.
        /// </summary>
        public string ApplicationId
        {
            get { return applicationId; }
            set { applicationId = value; }
        }

        /// <summary>
        /// The service version your application want to use,
        /// If not set, the latest version will be used. 
        /// </summary>
        public string ServiceVersion
        {
            get { return serviceVersion; }
            set { serviceVersion = value; }
        }

        /// <summary>
        /// The unique identifier for a combination of site, language, and territory.
        /// For example, EBAY-US (the default) is the global ID that corresponds to the
        /// eBay US site. The Global ID you specify must correspond to an eBay site with
        /// site ID. Refer to <a href="http://developer.ebay.com/devzone/finding/Concepts/SiteIDToGlobalID.html">eBay Site ID to Global ID Mapping</a>. 
        /// In addition, <a href="http://developer.ebay.com/devzone/finding/CallRef/Enums/GlobalIdList.html">Global ID Values</a> contains a complete list of the eBay global IDs.
        /// 
        /// If not set, defaut to EBAY-US.
        /// </summary>
        public string GlobalId
        {
            get { return globalId; }
            set { globalId = value; }
        }

        /// <summary>
        /// The service endpoint(either production or sandbox) you request will be sent to,
        /// this is mandatory.
        /// </summary>
        public string EndPointAddress
        {
            get { return endPointAddress; }
            set { endPointAddress = value; }
        }

        /// <summary>
        /// Should http compression be enabled or not, ignored in current client implementation
        /// </summary>
        public bool HttpCompressionEnabled
        {
            get { return httpCompressionEnabled; }
            set { httpCompressionEnabled = value; }
        }

        /// <summary>
        /// Should http headers be logged or not,
        /// default to true
        /// </summary>
        public bool HttpHeaderLoggingEnabled
        {
            get { return httpHeaderLoggingEnabled; }
            set { httpHeaderLoggingEnabled = value; }
        }

        /// <summary>
        /// Http request timeout setting, unit Milliseconds.
        /// will take effect only if the timeout value > 0, otherwise, WCF framework default value will be used.
        /// </summary>
        public int HttpTimeout
        {
            get { return httpTimeout; }
            set { httpTimeout = value; }
        }

        /// <summary>
        /// Should soap message to blooged or not,
        /// default to true
        /// </summary>
        public bool SoapMessageLoggingEnabled
        {
            get { return soapMessageLoggingEnabled; }
            set { soapMessageLoggingEnabled = value; }
        }

        #endregion
    }
}

主要功能的实现

//创建一个对象 FindingServicePortTypeClient
            FindingServicePortTypeClient client;
            //初始化log
            LoggerService.SetLogger(new TraceLogger());
            //从配置文件得到Appid 和服务地址e
            string appID = ConfigurationManager.AppSettings["AppID"];
            //获取搜索地址
            string findingServerAddress = ConfigurationManager.AppSettings["FindingServerAddress"];
            //初始化服务站点配置
            ClientConfig config = new ClientConfig();
            config.EndPointAddress = findingServerAddress;
            //设置EBAY开发人员账号
            config.ApplicationId = appID;
            client = FindingServiceClientFactory.getSerivceClient(config);
            //创建一个请求对象
            FindItemsByKeywordsRequest request = new FindItemsByKeywordsRequest();
            //调用请求对象的一个keywords属性
            request.keywords = "8 Pcs Neutral 18650 3.7V-4.2V 5000mAh Rechargeable Lithium Battery Deep Blue";
            //创建一个响应对象
            FindItemsByKeywordsResponse response = client.findItemsByKeywords(request);
            //创建一个用来得到返回的资源数组
            SearchItem[] results = response.searchResult.item;
            foreach (SearchItem item in results)
            {
                Console.WriteLine("商品item:{0}\r\n", item.itemId);
                Console.WriteLine("商品名称:{0}\r\n", item.title);
                Console.WriteLine("商品图片:{0}\r\n", item.galleryURL);
            }
keywords 属性后面是你想要搜索的商品

FindApi基本使用

标签:des   style   blog   http   color   os   使用   io   strong   

原文地址:http://www.cnblogs.com/caihuashun/p/3944607.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!