zoukankan      html  css  js  c++  java
  • Httwebrequest调用webservice

    webservice的webconfig配置,不配置后面会报远程服务器返回错误: (500) 内部服务器错误,跨域错误。

      <system.web>
        <compilation debug="true" targetFramework="4.0" />
        <webServices>
          <protocols>
            <add name= "HttpPost"/>
            <add name= "HttpGet"/>
          </protocols>
        </webServices>
      </system.web>
    <configuration>
     <system.webServer>  
        <httpProtocol>   
        <customHeaders>   
          <add name="Access-Control-Allow-Methods" value="OPTIONS,POST,GET"/>   
          <add name="Access-Control-Allow-Headers" value="x-requested-with,content-type"/>   
          <add name="Access-Control-Allow-Origin" value="*" />   
        </customHeaders>   
      </httpProtocol>   
      <modules>  
        <add name="MyHttpModule" type="WebServiceDemo.MyHttpModule"/>  
      </modules>
      </system.webServer>  
    </configuration>

    如果报错:

    未能加载类型“WebServiceDemo.MyHttpModule”。去掉

     <modules>  
        <add name="MyHttpModule" type="WebServiceDemo.MyHttpModule"/>  
      </modules>

    webserviceDemo.asmx

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Services;
    
    namespace News.webservice
    {
        /// <summary>
        /// WebServiceDemo 的摘要说明
        /// </summary>
        [WebService(Namespace = "http://tempuri.org/")]
        [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
        [System.ComponentModel.ToolboxItem(false)]
        // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。 
        [System.Web.Script.Services.ScriptService]
        public class WebServiceDemo : System.Web.Services.WebService
        {
    
            [WebMethod]
            public string HelloWorld(string name,string name1)
            {
                return name+name1;
            }
        }
    }

    前台调用

      $.ajax({
    		            type: "POST", //访问WebService使用Post方式请求
    		            contentType: "application/json;charset=utf-8", //WebService 会返回Json类型
    
    		            url: "http://localhost:1071/webservice/WebServiceDemo.asmx/HelloWorld",
    
    		            data: "{name:"" + 123 + ""}", //企业id参数
    		            dataType: 'json',
    		            beforeSend: function (x) { x.setRequestHeader("Content-Type", "application/json; charset=utf-8"); },
    		            error: function (x, e) { alert('fail'); },
    		            success: function (result) { //回调函数,result,返回值
    
    		                alert(JSON.stringify(result));
    		            }
    		        });
    

      

    后台调用  转自:http://www.cnblogs.com/ghelement/p/5286630.html 

      static void Main(string[] args)
            {
    
              string a=  GetStringByUrl("http://localhost:1071/webservice/WebServiceDemo.asmx/HelloWorld?name=youchim");
           
             
              string b= RequestWebService("http://localhost:1071/webservice/WebServiceDemo.asmx/HelloWorld","name=朱一届&name1=youchim");
            
              }
       //get
        public static string GetStringByUrl(string strUrl)
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strUrl);
                req.UserAgent = "MSIE6.0";
                req.Method = "GET";
                //http://www.cnblogs.com/cresuccess/archive/2009/12/09/1619977.html
                HttpWebResponse res;
                try
                {
                    res = (HttpWebResponse)req.GetResponse();
                }
                catch (WebException ex)
                {
                    res = (HttpWebResponse)ex.Response;
                }
              
             
                StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.GetEncoding("UTF-8"));
                string  strHtml = sr.ReadToEnd();
                sr.Close();
                res.Close();
                return strHtml;
               
            }
            //post方法
    
            public static string RequestWebService(string strUrl, string strPostData)
            {
                try
                {
                    //构造请求
                    HttpWebRequest hwrRequest = (HttpWebRequest)WebRequest.Create(strUrl);
                    hwrRequest.Method = "POST";
                    hwrRequest.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-shockwave-flash, */*";
                    hwrRequest.Headers.Add("Accept-Encoding", "gzip, deflate");
                    hwrRequest.Headers.Add("Accept-Language", "zh-cn");
                    hwrRequest.Headers.Add("Cache-Control", "gzip, deflate");
                    hwrRequest.Headers.Add("KeepAlive", "TRUE");
                    hwrRequest.Headers.Add("ContentLength", strPostData.Length.ToString());
                    hwrRequest.ContentType = "application/x-www-form-urlencoded";
                    hwrRequest.Referer = strUrl;
                    hwrRequest.Headers.Add("UA-CPU", "x86");
                    hwrRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
                    hwrRequest.Timeout = 30000;
                    hwrRequest.ServicePoint.Expect100Continue = false;
    
                    //发送请求
                    byte[] bytPostData = Encoding.UTF8.GetBytes(strPostData);
                    Stream strStream = hwrRequest.GetRequestStream();
                    strStream.Write(bytPostData, 0, bytPostData.Length);
                    strStream.Close();
    
                    //就收应答
                    HttpWebResponse hwrResponse = (HttpWebResponse)hwrRequest.GetResponse();
                    Stream strStream1 = null;
                    if (hwrResponse.ContentEncoding == "gzip")
                    {
                        System.IO.Compression.GZipStream gzsStream = new System.IO.Compression.GZipStream(hwrResponse.GetResponseStream(), System.IO.Compression.CompressionMode.Decompress);
                        strStream1 = gzsStream;
                    }
                    else
                    {
                        strStream1 = hwrResponse.GetResponseStream();
                    }
    
                    string strResult = new StreamReader(strStream1, System.Text.Encoding.UTF8).ReadToEnd();
                    hwrResponse.Close();
    
                    return strResult;
                }
                catch (Exception excResult)
                {
                    return "";
                }
            }            
  • 相关阅读:
    vue、vuex、iview、vue-router报错集锦与爬坑记录
    iview框架select默认选择一个option的值
    datetimerangepicker配置及默认时间段展示
    windows下nvm安装node之后npm命令找不到问题解决办法
    The difference between the request time and the current time is too large.阿里云oss上传图片报错
    html5 移动适配写法
    JS判断设备类型跳转至PC端或移动端相应页面
    vue2.0生命周期好文章推荐
    vue如何正确销毁当前组件的scroll事件?
    Apache Shiro 反序列化RCE漏洞
  • 原文地址:https://www.cnblogs.com/youchim/p/7337076.html
Copyright © 2011-2022 走看看