C#访问webservice的几种方式

C#访问webservice的几种方式

最近用C#做一个webservice的接口,尝试了好几种方式,今天把方式总结一下

第一种方式

添加服务引用,从项目右键添加引用那里添加,输入URL就可以了。如下图:

这种方式只可以访问部分的服务引用,并不能全部访问到

第二种方式

添加WEB服务引用

大多数.net都会使用这种方式来添加引用,优点是添加快速,不用去搞什么东西,缺点是有时候会访问不到其他人的webservice,各种弹窗出错。

第三种方式:网上常见的动态调用方式

在上面两种方式都尝试了不行的情况下,不如试试用一下的方式,下面是一个网上找到动态调用类。

  1.  
    using System;
  2.  
    using System.Collections.Generic;
  3.  
    using System.Linq;
  4.  
    using System.Web;
  5.  
    using System.Net;
  6.  
    using System.IO;
  7.  
    using System.Web.Services.Description;
  8.  
    using System.CodeDom;
  9.  
    using Microsoft.CSharp;
  10.  
    using System.CodeDom.Compiler;
  11.  
    using System.Reflection;
  12.  
    using System.Xml.Serialization;
  13.  
    using System.Text;
  14.  
     
  15.  
    namespace HTTPS
  16.  
    {
  17.  
    public class WSHelper
  18.  
    {
  19.  
    /// < summary>
  20.  
    /// 动态调用web服务
  21.  
    /// < /summary>
  22.  
    /// < param name="url">WSDL服务地址< /param>
  23.  
    /// < param name="methodname">方法名< /param>
  24.  
    /// < param name="args">参数< /param>
  25.  
    /// < returns>< /returns>
  26.  
    public static object InvokeWebService(string url, string methodname, object[] args)
  27.  
    {
  28.  
    return WSHelper.InvokeWebService(url, null, methodname, args);
  29.  
    }
  30.  
    /// < summary>
  31.  
    /// 动态调用web服务
  32.  
    /// < /summary>
  33.  
    /// < param name="url">WSDL服务地址< /param>
  34.  
    /// < param name="classname">类名< /param>
  35.  
    /// < param name="methodname">方法名< /param>
  36.  
    /// < param name="args">参数< /param>
  37.  
    /// < returns>< /returns>
  38.  
    public static object InvokeWebService(string url, string classname, string methodname, object[] args)
  39.  
    {
  40.  
    string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling";
  41.  
    if ((classname == null) || (classname == ""))
  42.  
    {
  43.  
    classname = WSHelper.GetWsClassName(url);
  44.  
    }
  45.  
    try
  46.  
    { //获取WSDL
  47.  
    WebClient wc = new WebClient();
  48.  
    Stream stream = wc.OpenRead(url + "?WSDL");
  49.  
    ServiceDescription sd = ServiceDescription.Read(stream);
  50.  
    ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
  51.  
    sdi.AddServiceDescription(sd, "", "");
  52.  
    CodeNamespace cn = new CodeNamespace(@namespace);
  53.  
    //生成客户端代理类代码
  54.  
    CodeCompileUnit ccu = new CodeCompileUnit();
  55.  
    ccu.Namespaces.Add(cn);
  56.  
    sdi.Import(cn, ccu);
  57.  
    CSharpCodeProvider icc = new CSharpCodeProvider();
  58.  
    //设定编译参数
  59.  
    CompilerParameters cplist = new CompilerParameters();
  60.  
    cplist.GenerateExecutable = false;
  61.  
    cplist.GenerateInMemory = true;
  62.  
    cplist.ReferencedAssemblies.Add( "System.dll");
  63.  
    cplist.ReferencedAssemblies.Add( "System.XML.dll");
  64.  
    cplist.ReferencedAssemblies.Add( "System.Web.Services.dll");
  65.  
    cplist.ReferencedAssemblies.Add( "System.Data.dll");
  66.  
    //编译代理类
  67.  
    CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);
  68.  
    if (true == cr.Errors.HasErrors)
  69.  
    {
  70.  
    System.Text.StringBuilder sb = new System.Text.StringBuilder();
  71.  
    foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
  72.  
    {
  73.  
    sb.Append(ce.ToString());
  74.  
    sb.Append(System.Environment.NewLine);
  75.  
    }
  76.  
    throw new Exception(sb.ToString());
  77.  
    }
  78.  
    //生成代理实例,并调用方法
  79.  
    System.Reflection.Assembly assembly = cr.CompiledAssembly;
  80.  
    Type t = assembly.GetType(@ namespace + "." + classname, true, true);
  81.  
    object obj = Activator.CreateInstance(t);
  82.  
    System.Reflection.MethodInfo mi = t.GetMethod(methodname);
  83.  
    return mi.Invoke(obj, args);
  84.  
    // PropertyInfo propertyInfo = type.GetProperty(propertyname);
  85.  
    //return propertyInfo.GetValue(obj, null);
  86.  
    }
  87.  
    catch (Exception ex)
  88.  
    {
  89.  
    throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
  90.  
    }
  91.  
    }
  92.  
    private static string GetWsClassName(string wsUrl)
  93.  
    {
  94.  
    string[] parts = wsUrl.Split('/');
  95.  
    string[] pps = parts[parts.Length - 1].Split('.');
  96.  
    return pps[0];
  97.  
    }
  98.  
     
  99.  
     
  100.  
    //上面那种方法的调用方式
  101.  
    //string url = "http://webservice.webxml.com.cn/WebServices/TrainTimeWebService.asmx";
  102.  
    //string[] args = new string[2];
  103.  
    //args[0] = "k123";
  104.  
    //args[1] = "";
  105.  
    //object result = WSHelper.InvokeWebService(url, "getDetailInfoByTrainCode", args);
  106.  
    //DataSet ds = (DataSet)result;
  107.  
    //this.GridView1.DataSource = ds;
  108.  
    //this.GridView1.DataBind();
  109.  
    }
  110.  
    }
详情可以看这里:http://blog.csdn.net/chuxiamuxiang/article/details/5731988

第四种方式:通过HTTP请求来调用

在上面的办法都试过之后,还是无法调用,那就需要通过HTTP请求来调用了,当然除了C#可以实现之外,JS也是可以的,但是JS会出现跨域的问题。

下面是一个HTTP操作类

  1.  
    using System;
  2.  
    using System.Collections.Generic;
  3.  
    using System.Text;
  4.  
    using System.Net;
  5.  
    using System.IO;
  6.  
    using System.Text.RegularExpressions;
  7.  
    using System.IO.Compression;
  8.  
    using System.Security.Cryptography.X509Certificates;
  9.  
    using System.Net.Security;
  10.  
     
  11.  
    namespace RuRo.Common
  12.  
    {
  13.  
    /// <summary>
  14.  
    /// Http连接操作帮助类
  15.  
    /// </summary>
  16.  
    public class HttpHelper
  17.  
    {
  18.  
    #region 预定义方变量
  19.  
    //默认的编码
  20.  
    private Encoding encoding = Encoding.Default;
  21.  
    //Post数据编码
  22.  
    private Encoding postencoding = Encoding.Default;
  23.  
    //HttpWebRequest对象用来发起请求
  24.  
    private HttpWebRequest request = null;
  25.  
    //获取影响流的数据对象
  26.  
    private HttpWebResponse response = null;
  27.  
    #endregion
  28.  
     
  29.  
    #region Public
  30.  
     
  31.  
    /// <summary>
  32.  
    /// 根据相传入的数据,得到相应页面数据
  33.  
    /// </summary>
  34.  
    /// <param name="item">参数类对象</param>
  35.  
    /// <returns>返回HttpResult类型</returns>
  36.  
    public HttpResult GetHtml(HttpItem item)
  37.  
    {
  38.  
    //返回参数
  39.  
    HttpResult result = new HttpResult();
  40.  
    try
  41.  
    {
  42.  
    //准备参数
  43.  
    SetRequest(item);
  44.  
    }
  45.  
    catch (Exception ex)
  46.  
    {
  47.  
    result.Cookie = string.Empty;
  48.  
    result.Header = null;
  49.  
    result.Html = ex.Message;
  50.  
    result.StatusDescription = "配置参数时出错:" + ex.Message;
  51.  
    //配置参数时出错
  52.  
    return result;
  53.  
    }
  54.  
    try
  55.  
    {
  56.  
    //请求数据
  57.  
    using (response = (HttpWebResponse)request.GetResponse())
  58.  
    {
  59.  
    GetData(item, result);
  60.  
    }
  61.  
    }
  62.  
    catch (WebException ex)
  63.  
    {
  64.  
    if (ex.Response != null)
  65.  
    {
  66.  
    using (response = (HttpWebResponse)ex.Response)
  67.  
    {
  68.  
    GetData(item, result);
  69.  
    }
  70.  
    }
  71.  
    else
  72.  
    {
  73.  
    result.Html = ex.Message;
  74.  
    }
  75.  
    }
  76.  
    catch (Exception ex)
  77.  
    {
  78.  
    result.Html = ex.Message;
  79.  
    }
  80.  
    if (item.IsToLower) result.Html = result.Html.ToLower();
  81.  
    return result;
  82.  
    }
  83.  
    #endregion
  84.  
     
  85.  
    #region GetData
  86.  
     
  87.  
    /// <summary>
  88.  
    /// 获取数据的并解析的方法
  89.  
    /// </summary>
  90.  
    /// <param name="item"></param>
  91.  
    /// <param name="result"></param>
  92.  
    private void GetData(HttpItem item, HttpResult result)
  93.  
    {
  94.  
    #region base
  95.  
    //获取StatusCode
  96.  
    result.StatusCode = response.StatusCode;
  97.  
    //获取StatusDescription
  98.  
    result.StatusDescription = response.StatusDescription;
  99.  
    //获取Headers
  100.  
    result.Header = response.Headers;
  101.  
    //获取CookieCollection
  102.  
    if (response.Cookies != null) result.CookieCollection = response.Cookies;
  103.  
    //获取set-cookie
  104.  
    if (response.Headers["set-cookie"] != null) result.Cookie = response.Headers["set-cookie"];
  105.  
    #endregion
  106.  
     
  107.  
    #region byte
  108.  
    //处理网页Byte
  109.  
    byte[] ResponseByte = GetByte();
  110.  
    #endregion
  111.  
     
  112.  
    #region Html
  113.  
    if (ResponseByte != null & ResponseByte.Length > 0)
  114.  
    {
  115.  
    //设置编码
  116.  
    SetEncoding(item, result, ResponseByte);
  117.  
    //得到返回的HTML
  118.  
    result.Html = encoding.GetString(ResponseByte);
  119.  
    }
  120.  
    else
  121.  
    {
  122.  
    //没有返回任何Html代码
  123.  
    result.Html = string.Empty;
  124.  
    }
  125.  
    #endregion
  126.  
    }
  127.  
    /// <summary>
  128.  
    /// 设置编码
  129.  
    /// </summary>
  130.  
    /// <param name="item">HttpItem</param>
  131.  
    /// <param name="result">HttpResult</param>
  132.  
    /// <param name="ResponseByte">byte[]</param>
  133.  
    private void SetEncoding(HttpItem item, HttpResult result, byte[] ResponseByte)
  134.  
    {
  135.  
    //是否返回Byte类型数据
  136.  
    if (item.ResultType == ResultType.Byte) result.ResultByte = ResponseByte;
  137.  
    //从这里开始我们要无视编码了
  138.  
    if (encoding == null)
  139.  
    {
  140.  
    Match meta = Regex.Match(Encoding.Default.GetString(ResponseByte), "<meta[^<]*charset=([^<]*)[\"']", RegexOptions.IgnoreCase);
  141.  
    string c = string.Empty;
  142.  
    if (meta != null && meta.Groups.Count > 0)
  143.  
    {
  144.  
    c = meta.Groups[ 1].Value.ToLower().Trim();
  145.  
    }
  146.  
    if (c.Length > 2)
  147.  
    {
  148.  
    try
  149.  
    {
  150.  
    encoding = Encoding.GetEncoding(c.Replace( "\"", string.Empty).Replace("'", "").Replace(";", "").Replace("iso-8859-1", "gbk").Trim());
  151.  
    }
  152.  
    catch
  153.  
    {
  154.  
    if (string.IsNullOrEmpty(response.CharacterSet))
  155.  
    {
  156.  
    encoding = Encoding.UTF8;
  157.  
    }
  158.  
    else
  159.  
    {
  160.  
    encoding = Encoding.GetEncoding(response.CharacterSet);
  161.  
    }
  162.  
    }
  163.  
    }
  164.  
    else
  165.  
    {
  166.  
    if (string.IsNullOrEmpty(response.CharacterSet))
  167.  
    {
  168.  
    encoding = Encoding.UTF8;
  169.  
    }
  170.  
    else
  171.  
    {
  172.  
    encoding = Encoding.GetEncoding(response.CharacterSet);
  173.  
    }
  174.  
    }
  175.  
    }
  176.  
    }
  177.  
    /// <summary>
  178.  
    /// 提取网页Byte
  179.  
    /// </summary>
  180.  
    /// <returns></returns>
  181.  
    private byte[] GetByte()
  182.  
    {
  183.  
    byte[] ResponseByte = null;
  184.  
    MemoryStream _stream = new MemoryStream();
  185.  
     
  186.  
    //GZIIP处理
  187.  
    if (response.ContentEncoding != null && response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase))
  188.  
    {
  189.  
    //开始读取流并设置编码方式
  190.  
    _stream = GetMemoryStream( new GZipStream(response.GetResponseStream(), CompressionMode.Decompress));
  191.  
    }
  192.  
    else
  193.  
    {
  194.  
    //开始读取流并设置编码方式
  195.  
    _stream = GetMemoryStream(response.GetResponseStream());
  196.  
    }
  197.  
    //获取Byte
  198.  
    ResponseByte = _stream.ToArray();
  199.  
    _stream.Close();
  200.  
    return ResponseByte;
  201.  
    }
  202.  
     
  203.  
    /// <summary>
  204.  
    /// 4.0以下.net版本取数据使用
  205.  
    /// </summary>
  206.  
    /// <param name="streamResponse">流</param>
  207.  
    private MemoryStream GetMemoryStream(Stream streamResponse)
  208.  
    {
  209.  
    MemoryStream _stream = new MemoryStream();
  210.  
    int Length = 256;
  211.  
    Byte[] buffer = new Byte[Length];
  212.  
    int bytesRead = streamResponse.Read(buffer, 0, Length);
  213.  
    while (bytesRead > 0)
  214.  
    {
  215.  
    _stream.Write(buffer, 0, bytesRead);
  216.  
    bytesRead = streamResponse.Read(buffer, 0, Length);
  217.  
    }
  218.  
    return _stream;
  219.  
    }
  220.  
    #endregion
  221.  
     
  222.  
    #region SetRequest
  223.  
     
  224.  
    /// <summary>
  225.  
    /// 为请求准备参数
  226.  
    /// </summary>
  227.  
    ///<param name="item">参数列表</param>
  228.  
    private void SetRequest(HttpItem item)
  229.  
    {
  230.  
    // 验证证书
  231.  
    SetCer(item);
  232.  
    //设置Header参数
  233.  
    if (item.Header != null && item.Header.Count > 0) foreach (string key in item.Header.AllKeys)
  234.  
    {
  235.  
    request.Headers.Add(key, item.Header[key]);
  236.  
    }
  237.  
    // 设置代理
  238.  
    SetProxy(item);
  239.  
    if (item.ProtocolVersion != null) request.ProtocolVersion = item.ProtocolVersion;
  240.  
    request.ServicePoint.Expect100Continue = item.Expect100Continue;
  241.  
    //请求方式Get或者Post
  242.  
    request.Method = item.Method;
  243.  
    request.Timeout = item.Timeout;
  244.  
    request.KeepAlive = item.KeepAlive;
  245.  
    request.ReadWriteTimeout = item.ReadWriteTimeout;
  246.  
    if (item.IfModifiedSince != null) request.IfModifiedSince = Convert.ToDateTime(item.IfModifiedSince);
  247.  
    //Accept
  248.  
    request.Accept = item.Accept;
  249.  
    //ContentType返回类型
  250.  
    request.ContentType = item.ContentType;
  251.  
    //UserAgent客户端的访问类型,包括浏览器版本和操作系统信息
  252.  
    request.UserAgent = item.UserAgent;
  253.  
    // 编码
  254.  
    encoding = item.Encoding;
  255.  
    //设置安全凭证
  256.  
    request.Credentials = item.ICredentials;
  257.  
    //设置Cookie
  258.  
    SetCookie(item);
  259.  
    //来源地址
  260.  
    request.Referer = item.Referer;
  261.  
    //是否执行跳转功能
  262.  
    request.AllowAutoRedirect = item.Allowautoredirect;
  263.  
    if (item.MaximumAutomaticRedirections > 0)
  264.  
    {
  265.  
    request.MaximumAutomaticRedirections = item.MaximumAutomaticRedirections;
  266.  
    }
  267.  
    //设置Post数据
  268.  
    SetPostData(item);
  269.  
    //设置最大连接
  270.  
    if (item.Connectionlimit > 0) request.ServicePoint.ConnectionLimit = item.Connectionlimit;
  271.  
    }
  272.  
    /// <summary>
  273.  
    /// 设置证书
  274.  
    /// </summary>
  275.  
    /// <param name="item"></param>
  276.  
    private void SetCer(HttpItem item)
  277.  
    {
  278.  
    if (!string.IsNullOrEmpty(item.CerPath))
  279.  
    {
  280.  
    //这一句一定要写在创建连接的前面。使用回调的方法进行证书验证。
  281.  
    ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
  282.  
    //初始化对像,并设置请求的URL地址
  283.  
    request = (HttpWebRequest)WebRequest.Create(item.URL);
  284.  
    SetCerList(item);
  285.  
    //将证书添加到请求里
  286.  
    request.ClientCertificates.Add( new X509Certificate(item.CerPath));
  287.  
    }
  288.  
    else
  289.  
    {
  290.  
    //初始化对像,并设置请求的URL地址
  291.  
    request = (HttpWebRequest)WebRequest.Create(item.URL);
  292.  
    SetCerList(item);
  293.  
    }
  294.  
    }
  295.  
    /// <summary>
  296.  
    /// 设置多个证书
  297.  
    /// </summary>
  298.  
    /// <param name="item"></param>
  299.  
    private void SetCerList(HttpItem item)
  300.  
    {
  301.  
    if (item.ClentCertificates != null && item.ClentCertificates.Count > 0)
  302.  
    {
  303.  
    foreach (X509Certificate c in item.ClentCertificates)
  304.  
    {
  305.  
    request.ClientCertificates.Add(c);
  306.  
    }
  307.  
    }
  308.  
    }
  309.  
    /// <summary>
  310.  
    /// 设置Cookie
  311.  
    /// </summary>
  312.  
    /// <param name="item">Http参数</param>
  313.  
    private void SetCookie(HttpItem item)
  314.  
    {
  315.  
    if (!string.IsNullOrEmpty(item.Cookie)) request.Headers[HttpRequestHeader.Cookie] = item.Cookie;
  316.  
    //设置CookieCollection
  317.  
    if (item.ResultCookieType == ResultCookieType.CookieCollection)
  318.  
    {
  319.  
    request.CookieContainer = new CookieContainer();
  320.  
    if (item.CookieCollection != null && item.CookieCollection.Count > 0)
  321.  
    request.CookieContainer.Add(item.CookieCollection);
  322.  
    }
  323.  
    }
  324.  
    /// <summary>
  325.  
    /// 设置Post数据
  326.  
    /// </summary>
  327.  
    /// <param name="item">Http参数</param>
  328.  
    private void SetPostData(HttpItem item)
  329.  
    {
  330.  
    //验证在得到结果时是否有传入数据
  331.  
    if (!request.Method.Trim().ToLower().Contains("get"))
  332.  
    {
  333.  
    if (item.PostEncoding != null)
  334.  
    {
  335.  
    postencoding = item.PostEncoding;
  336.  
    }
  337.  
    byte[] buffer = null;
  338.  
    //写入Byte类型
  339.  
    if (item.PostDataType == PostDataType.Byte && item.PostdataByte != null && item.PostdataByte.Length > 0)
  340.  
    {
  341.  
    //验证在得到结果时是否有传入数据
  342.  
    buffer = item.PostdataByte;
  343.  
    } //写入文件
  344.  
    else if (item.PostDataType == PostDataType.FilePath && !string.IsNullOrEmpty(item.Postdata))
  345.  
    {
  346.  
    StreamReader r = new StreamReader(item.Postdata, postencoding);
  347.  
    buffer = postencoding.GetBytes(r.ReadToEnd());
  348.  
    r.Close();
  349.  
    } //写入字符串
  350.  
    else if (!string.IsNullOrEmpty(item.Postdata))
  351.  
    {
  352.  
    buffer = postencoding.GetBytes(item.Postdata);
  353.  
    }
  354.  
    if (buffer != null)
  355.  
    {
  356.  
    request.ContentLength = buffer.Length;
  357.  
    request.GetRequestStream().Write(buffer, 0, buffer.Length);
  358.  
    }
  359.  
    }
  360.  
    }
  361.  
    /// <summary>
  362.  
    /// 设置代理
  363.  
    /// </summary>
  364.  
    /// <param name="item">参数对象</param>
  365.  
    private void SetProxy(HttpItem item)
  366.  
    {
  367.  
    bool isIeProxy = false;
  368.  
    if (!string.IsNullOrEmpty(item.ProxyIp))
  369.  
    {
  370.  
    isIeProxy = item.ProxyIp.ToLower().Contains( "ieproxy");
  371.  
    }
  372.  
    if (!string.IsNullOrEmpty(item.ProxyIp) && !isIeProxy)
  373.  
    {
  374.  
    //设置代理服务器
  375.  
    if (item.ProxyIp.Contains(":"))
  376.  
    {
  377.  
    string[] plist = item.ProxyIp.Split(':');
  378.  
    WebProxy myProxy = new WebProxy(plist[0].Trim(), Convert.ToInt32(plist[1].Trim()));
  379.  
    //建议连接
  380.  
    myProxy.Credentials = new NetworkCredential(item.ProxyUserName, item.ProxyPwd);
  381.  
    //给当前请求对象
  382.  
    request.Proxy = myProxy;
  383.  
    }
  384.  
    else
  385.  
    {
  386.  
    WebProxy myProxy = new WebProxy(item.ProxyIp, false);
  387.  
    //建议连接
  388.  
    myProxy.Credentials = new NetworkCredential(item.ProxyUserName, item.ProxyPwd);
  389.  
    //给当前请求对象
  390.  
    request.Proxy = myProxy;
  391.  
    }
  392.  
    }
  393.  
    else if (isIeProxy)
  394.  
    {
  395.  
    //设置为IE代理
  396.  
    }
  397.  
    else
  398.  
    {
  399.  
    request.Proxy = item.WebProxy;
  400.  
    }
  401.  
    }
  402.  
    #endregion
  403.  
     
  404.  
    #region private main
  405.  
    /// <summary>
  406.  
    /// 回调验证证书问题
  407.  
    /// </summary>
  408.  
    /// <param name="sender">流对象</param>
  409.  
    /// <param name="certificate">证书</param>
  410.  
    /// <param name="chain">X509Chain</param>
  411.  
    /// <param name="errors">SslPolicyErrors</param>
  412.  
    /// <returns>bool</returns>
  413.  
    private bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; }
  414.  
    #endregion
  415.  
     
  416.  
     
  417.  
    }
  418.  
    /// <summary>
  419.  
    /// Http请求参考类
  420.  
    /// </summary>
  421.  
    public class HttpItem
  422.  
    {
  423.  
    string _URL = string.Empty;
  424.  
    /// <summary>
  425.  
    /// 请求URL必须填写
  426.  
    /// </summary>
  427.  
    public string URL
  428.  
    {
  429.  
    get { return _URL; }
  430.  
    set { _URL = value; }
  431.  
    }
  432.  
    string _Method = "GET";
  433.  
    /// <summary>
  434.  
    /// 请求方式默认为GET方式,当为POST方式时必须设置Postdata的值
  435.  
    /// </summary>
  436.  
    public string Method
  437.  
    {
  438.  
    get { return _Method; }
  439.  
    set { _Method = value; }
  440.  
    }
  441.  
    int _Timeout = 100000;
  442.  
    /// <summary>
  443.  
    /// 默认请求超时时间
  444.  
    /// </summary>
  445.  
    public int Timeout
  446.  
    {
  447.  
    get { return _Timeout; }
  448.  
    set { _Timeout = value; }
  449.  
    }
  450.  
    int _ReadWriteTimeout = 30000;
  451.  
    /// <summary>
  452.  
    /// 默认写入Post数据超时间
  453.  
    /// </summary>
  454.  
    public int ReadWriteTimeout
  455.  
    {
  456.  
    get { return _ReadWriteTimeout; }
  457.  
    set { _ReadWriteTimeout = value; }
  458.  
    }
  459.  
    Boolean _KeepAlive = true;
  460.  
    /// <summary>
  461.  
    /// 获取或设置一个值,该值指示是否与 Internet 资源建立持久性连接默认为true。
  462.  
    /// </summary>
  463.  
    public Boolean KeepAlive
  464.  
    {
  465.  
    get { return _KeepAlive; }
  466.  
    set { _KeepAlive = value; }
  467.  
    }
  468.  
    string _Accept = "text/html, application/xhtml+xml, */*";
  469.  
    /// <summary>
  470.  
    /// 请求标头值 默认为text/html, application/xhtml+xml, */*
  471.  
    /// </summary>
  472.  
    public string Accept
  473.  
    {
  474.  
    get { return _Accept; }
  475.  
    set { _Accept = value; }
  476.  
    }
  477.  
    string _ContentType = "text/html";
  478.  
    /// <summary>
  479.  
    /// 请求返回类型默认 text/html
  480.  
    /// </summary>
  481.  
    public string ContentType
  482.  
    {
  483.  
    get { return _ContentType; }
  484.  
    set { _ContentType = value; }
  485.  
    }
  486.  
    string _UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)";
  487.  
    /// <summary>
  488.  
    /// 客户端访问信息默认Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)
  489.  
    /// </summary>
  490.  
    public string UserAgent
  491.  
    {
  492.  
    get { return _UserAgent; }
  493.  
    set { _UserAgent = value; }
  494.  
    }
  495.  
    Encoding _Encoding = null;
  496.  
    /// <summary>
  497.  
    /// 返回数据编码默认为NUll,可以自动识别,一般为utf-8,gbk,gb2312
  498.  
    /// </summary>
  499.  
    public Encoding Encoding
  500.  
    {
  501.  
    get { return _Encoding; }
  502.  
    set { _Encoding = value; }
  503.  
    }
  504.  
    private PostDataType _PostDataType = PostDataType.String;
  505.  
    /// <summary>
  506.  
    /// Post的数据类型
  507.  
    /// </summary>
  508.  
    public PostDataType PostDataType
  509.  
    {
  510.  
    get { return _PostDataType; }
  511.  
    set { _PostDataType = value; }
  512.  
    }
  513.  
    string _Postdata = string.Empty;
  514.  
    /// <summary>
  515.  
    /// Post请求时要发送的字符串Post数据
  516.  
    /// </summary>
  517.  
    public string Postdata
  518.  
    {
  519.  
    get { return _Postdata; }
  520.  
    set { _Postdata = value; }
  521.  
    }
  522.  
    private byte[] _PostdataByte = null;
  523.  
    /// <summary>
  524.  
    /// Post请求时要发送的Byte类型的Post数据
  525.  
    /// </summary>
  526.  
    public byte[] PostdataByte
  527.  
    {
  528.  
    get { return _PostdataByte; }
  529.  
    set { _PostdataByte = value; }
  530.  
    }
  531.  
    private WebProxy _WebProxy;
  532.  
    /// <summary>
  533.  
    /// 设置代理对象,不想使用IE默认配置就设置为Null,而且不要设置ProxyIp
  534.  
    /// </summary>
  535.  
    public WebProxy WebProxy
  536.  
    {
  537.  
    get { return _WebProxy; }
  538.  
    set { _WebProxy = value; }
  539.  
    }
  540.  
     
  541.  
    CookieCollection cookiecollection = null;
  542.  
    /// <summary>
  543.  
    /// Cookie对象集合
  544.  
    /// </summary>
  545.  
    public CookieCollection CookieCollection
  546.  
    {
  547.  
    get { return cookiecollection; }
  548.  
    set { cookiecollection = value; }
  549.  
    }
  550.  
    string _Cookie = string.Empty;
  551.  
    /// <summary>
  552.  
    /// 请求时的Cookie
  553.  
    /// </summary>
  554.  
    public string Cookie
  555.  
    {
  556.  
    get { return _Cookie; }
  557.  
    set { _Cookie = value; }
  558.  
    }
  559.  
    string _Referer = string.Empty;
  560.  
    /// <summary>
  561.  
    /// 来源地址,上次访问地址
  562.  
    /// </summary>
  563.  
    public string Referer
  564.  
    {
  565.  
    get { return _Referer; }
  566.  
    set { _Referer = value; }
  567.  
    }
  568.  
    string _CerPath = string.Empty;
  569.  
    /// <summary>
  570.  
    /// 证书绝对路径
  571.  
    /// </summary>
  572.  
    public string CerPath
  573.  
    {
  574.  
    get { return _CerPath; }
  575.  
    set { _CerPath = value; }
  576.  
    }
  577.  
    private Boolean isToLower = false;
  578.  
    /// <summary>
  579.  
    /// 是否设置为全文小写,默认为不转化
  580.  
    /// </summary>
  581.  
    public Boolean IsToLower
  582.  
    {
  583.  
    get { return isToLower; }
  584.  
    set { isToLower = value; }
  585.  
    }
  586.  
    private Boolean allowautoredirect = false;
  587.  
    /// <summary>
  588.  
    /// 支持跳转页面,查询结果将是跳转后的页面,默认是不跳转
  589.  
    /// </summary>
  590.  
    public Boolean Allowautoredirect
  591.  
    {
  592.  
    get { return allowautoredirect; }
  593.  
    set { allowautoredirect = value; }
  594.  
    }
  595.  
    private int connectionlimit = 1024;
  596.  
    /// <summary>
  597.  
    /// 最大连接数
  598.  
    /// </summary>
  599.  
    public int Connectionlimit
  600.  
    {
  601.  
    get { return connectionlimit; }
  602.  
    set { connectionlimit = value; }
  603.  
    }
  604.  
    private string proxyusername = string.Empty;
  605.  
    /// <summary>
  606.  
    /// 代理Proxy 服务器用户名
  607.  
    /// </summary>
  608.  
    public string ProxyUserName
  609.  
    {
  610.  
    get { return proxyusername; }
  611.  
    set { proxyusername = value; }
  612.  
    }
  613.  
    private string proxypwd = string.Empty;
  614.  
    /// <summary>
  615.  
    /// 代理 服务器密码
  616.  
    /// </summary>
  617.  
    public string ProxyPwd
  618.  
    {
  619.  
    get { return proxypwd; }
  620.  
    set { proxypwd = value; }
  621.  
    }
  622.  
    private string proxyip = string.Empty;
  623.  
    /// <summary>
  624.  
    /// 代理 服务IP ,如果要使用IE代理就设置为ieproxy
  625.  
    /// </summary>
  626.  
    public string ProxyIp
  627.  
    {
  628.  
    get { return proxyip; }
  629.  
    set { proxyip = value; }
  630.  
    }
  631.  
    private ResultType resulttype = ResultType.String;
  632.  
     
  633.  
    /// <summary>
  634.  
    /// 设置返回类型String和Byte
  635.  
    /// </summary>
  636.  
    public ResultType ResultType
  637.  
    {
  638.  
    get { return resulttype; }
  639.  
    set { resulttype = value; }
  640.  
    }
  641.  
    private WebHeaderCollection header = new WebHeaderCollection();
  642.  
    /// <summary>
  643.  
    /// header对象
  644.  
    /// </summary>
  645.  
    public WebHeaderCollection Header
  646.  
    {
  647.  
    get { return header; }
  648.  
    set { header = value; }
  649.  
    }
  650.  
     
  651.  
    private Version _ProtocolVersion;
  652.  
     
  653.  
    /// <summary>
  654.  
    // 获取或设置用于请求的 HTTP 版本。返回结果:用于请求的 HTTP 版本。默认为 System.Net.HttpVersion.Version11。
  655.  
    /// </summary>
  656.  
    public Version ProtocolVersion
  657.  
    {
  658.  
    get { return _ProtocolVersion; }
  659.  
    set { _ProtocolVersion = value; }
  660.  
    }
  661.  
    private Boolean _expect100continue = true;
  662.  
    /// <summary>
  663.  
    /// 获取或设置一个 System.Boolean 值,该值确定是否使用 100-Continue 行为。如果 POST 请求需要 100-Continue 响应,则为 true;否则为 false。默认值为 true。
  664.  
    /// </summary>
  665.  
    public Boolean Expect100Continue
  666.  
    {
  667.  
    get { return _expect100continue; }
  668.  
    set { _expect100continue = value; }
  669.  
    }
  670.  
    private X509CertificateCollection _ClentCertificates;
  671.  
    /// <summary>
  672.  
    /// 设置509证书集合
  673.  
    /// </summary>
  674.  
    public X509CertificateCollection ClentCertificates
  675.  
    {
  676.  
    get { return _ClentCertificates; }
  677.  
    set { _ClentCertificates = value; }
  678.  
    }
  679.  
    private Encoding _PostEncoding;
  680.  
    /// <summary>
  681.  
    /// 设置或获取Post参数编码,默认的为Default编码
  682.  
    /// </summary>
  683.  
    public Encoding PostEncoding
  684.  
    {
  685.  
    get { return _PostEncoding; }
  686.  
    set { _PostEncoding = value; }
  687.  
    }
  688.  
    private ResultCookieType _ResultCookieType = ResultCookieType.String;
  689.  
    /// <summary>
  690.  
    /// Cookie返回类型,默认的是只返回字符串类型
  691.  
    /// </summary>
  692.  
    public ResultCookieType ResultCookieType
  693.  
    {
  694.  
    get { return _ResultCookieType; }
  695.  
    set { _ResultCookieType = value; }
  696.  
    }
  697.  
     
  698.  
    private ICredentials _ICredentials = CredentialCache.DefaultCredentials;
  699.  
    /// <summary>
  700.  
    /// 获取或设置请求的身份验证信息。
  701.  
    /// </summary>
  702.  
    public ICredentials ICredentials
  703.  
    {
  704.  
    get { return _ICredentials; }
  705.  
    set { _ICredentials = value; }
  706.  
    }
  707.  
    /// <summary>
  708.  
    /// 设置请求将跟随的重定向的最大数目
  709.  
    /// </summary>
  710.  
    private int _MaximumAutomaticRedirections;
  711.  
     
  712.  
    public int MaximumAutomaticRedirections
  713.  
    {
  714.  
    get { return _MaximumAutomaticRedirections; }
  715.  
    set { _MaximumAutomaticRedirections = value; }
  716.  
    }
  717.  
     
  718.  
    private DateTime? _IfModifiedSince = null;
  719.  
    /// <summary>
  720.  
    /// 获取和设置IfModifiedSince,默认为当前日期和时间
  721.  
    /// </summary>
  722.  
    public DateTime? IfModifiedSince
  723.  
    {
  724.  
    get { return _IfModifiedSince; }
  725.  
    set { _IfModifiedSince = value; }
  726.  
    }
  727.  
     
  728.  
    }
  729.  
    /// <summary>
  730.  
    /// Http返回参数类
  731.  
    /// </summary>
  732.  
    public class HttpResult
  733.  
    {
  734.  
    private string _Cookie;
  735.  
    /// <summary>
  736.  
    /// Http请求返回的Cookie
  737.  
    /// </summary>
  738.  
    public string Cookie
  739.  
    {
  740.  
    get { return _Cookie; }
  741.  
    set { _Cookie = value; }
  742.  
    }
  743.  
     
  744.  
    private CookieCollection _CookieCollection;
  745.  
    /// <summary>
  746.  
    /// Cookie对象集合
  747.  
    /// </summary>
  748.  
    public CookieCollection CookieCollection
  749.  
    {
  750.  
    get { return _CookieCollection; }
  751.  
    set { _CookieCollection = value; }
  752.  
    }
  753.  
    private string _html = string.Empty;
  754.  
    /// <summary>
  755.  
    /// 返回的String类型数据 只有ResultType.String时才返回数据,其它情况为空
  756.  
    /// </summary>
  757.  
    public string Html
  758.  
    {
  759.  
    get { return _html; }
  760.  
    set { _html = value; }
  761.  
    }
  762.  
    private byte[] _ResultByte;
  763.  
    /// <summary>
  764.  
    /// 返回的Byte数组 只有ResultType.Byte时才返回数据,其它情况为空
  765.  
    /// </summary>
  766.  
    public byte[] ResultByte
  767.  
    {
  768.  
    get { return _ResultByte; }
  769.  
    set { _ResultByte = value; }
  770.  
    }
  771.  
    private WebHeaderCollection _Header;
  772.  
    /// <summary>
  773.  
    /// header对象
  774.  
    /// </summary>
  775.  
    public WebHeaderCollection Header
  776.  
    {
  777.  
    get { return _Header; }
  778.  
    set { _Header = value; }
  779.  
    }
  780.  
    private string _StatusDescription;
  781.  
    /// <summary>
  782.  
    /// 返回状态说明
  783.  
    /// </summary>
  784.  
    public string StatusDescription
  785.  
    {
  786.  
    get { return _StatusDescription; }
  787.  
    set { _StatusDescription = value; }
  788.  
    }
  789.  
    private HttpStatusCode _StatusCode;
  790.  
    /// <summary>
  791.  
    /// 返回状态码,默认为OK
  792.  
    /// </summary>
  793.  
    public HttpStatusCode StatusCode
  794.  
    {
  795.  
    get { return _StatusCode; }
  796.  
    set { _StatusCode = value; }
  797.  
    }
  798.  
    }
  799.  
    /// <summary>
  800.  
    /// 返回类型
  801.  
    /// </summary>
  802.  
    public enum ResultType
  803.  
    {
  804.  
    /// <summary>
  805.  
    /// 表示只返回字符串 只有Html有数据
  806.  
    /// </summary>
  807.  
    String,
  808.  
    /// <summary>
  809.  
    /// 表示返回字符串和字节流 ResultByte和Html都有数据返回
  810.  
    /// </summary>
  811.  
    Byte
  812.  
    }
  813.  
    /// <summary>
  814.  
    /// Post的数据格式默认为string
  815.  
    /// </summary>
  816.  
    public enum PostDataType
  817.  
    {
  818.  
    /// <summary>
  819.  
    /// 字符串类型,这时编码Encoding可不设置
  820.  
    /// </summary>
  821.  
    String,
  822.  
    /// <summary>
  823.  
    /// Byte类型,需要设置PostdataByte参数的值编码Encoding可设置为空
  824.  
    /// </summary>
  825.  
    Byte,
  826.  
    /// <summary>
  827.  
    /// 传文件,Postdata必须设置为文件的绝对路径,必须设置Encoding的值
  828.  
    /// </summary>
  829.  
    FilePath
  830.  
    }
  831.  
    /// <summary>
  832.  
    /// Cookie返回类型
  833.  
    /// </summary>
  834.  
    public enum ResultCookieType
  835.  
    {
  836.  
    /// <summary>
  837.  
    /// 只返回字符串类型的Cookie
  838.  
    /// </summary>
  839.  
    String,
  840.  
    /// <summary>
  841.  
    /// CookieCollection格式的Cookie集合同时也返回String类型的cookie
  842.  
    /// </summary>
  843.  
    CookieCollection
  844.  
    }
  845.  
     
  846.  
     
  847.  
    }
这里是调用的方式
  1.  
    public string PostData()
  2.  
    {
  3.  
    StringBuilder jsonData = new StringBuilder();
  4.  
    HttpHelper http = new HttpHelper();
  5.  
    HttpItem item = new HttpItem()
  6.  
    {
  7.  
    URL = "WWW.BAIDU.COM",//URL 必需项
  8.  
    Method = "post",//URL 可选项 默认为Get
  9.  
    IsToLower = false,//得到的HTML代码是否转成小写 可选项默认转小写
  10.  
    Cookie = "",//字符串Cookie 可选项
  11.  
    Referer = "",//来源URL 可选项
  12.  
    Postdata = jsonData.ToString(), //Post数据 可选项GET时不需要写
  13.  
    PostEncoding = Encoding.UTF8,
  14.  
    Timeout = 100000,//连接超时时间 可选项默认为100000
  15.  
    ReadWriteTimeout = 30000,//写入Post数据超时时间 可选项默认为30000
  16.  
    UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)",//用户的浏览器类型,版本,操作系统 可选项有默认值
  17.  
    ContentType = "application/x-www-form-urlencoded",//返回类型 可选项有默认值
  18.  
    Allowautoredirect = true,//是否根据301跳转 可选项
  19.  
    //CerPath = "d:\123.cer",//证书绝对路径 可选项不需要证书时可以不写这个参数
  20.  
    //Connectionlimit = 1024,//最大连接数 可选项 默认为1024
  21.  
    ProxyIp = "",//代理服务器ID 可选项 不需要代理 时可以不设置这三个参数
  22.  
    //ProxyPwd = "123456",//代理服务器密码 可选项
  23.  
    //ProxyUserName = "administrator",//代理服务器账户名 可选项
  24.  
    ResultType = ResultType.String
  25.  
    };
  26.  
    HttpResult result = http.GetHtml(item);
  27.  
    string html = result.Html;
  28.  
    string cookie = result.Cookie;
  29.  
    return html;
  30.  
    }

最近调用一个JAVA的WebService,调用不上去,搞得我非常郁闷,试到最后面,还是通过HTTP请求才获取到数据。很郁闷!

其实WebService都是用来跨平台的,任何语言都可以互相引用,多尝试几遍总有好办法。

猜你喜欢

转载自www.cnblogs.com/hbtmwangjin/p/9486714.html