前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >.net服务器端发起请求封装

.net服务器端发起请求封装

作者头像
用户1055830
发布2018-05-28 17:44:23
8930
发布2018-05-28 17:44:23
举报
文章被收录于专栏:飞扬的花生

写一个静态类封装类似客户端的请求

代码语言:javascript
复制
 public static class HttpHelper
    {
        #region Get
        public static string HttpGet(string url, Encoding encoding = null)
        {
            WebClient client = new WebClient
            {
                Encoding = encoding ?? Encoding.UTF8
            };
            return client.DownloadString(url);
        }

        /// <summary>
        /// Get请求的泛型类返回固定类型
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static T GetJson<T>(string url, Encoding encoding = null)
        {
            string input = HttpGet(url, encoding);
            JavaScriptSerializer serializer = new JavaScriptSerializer();

            return serializer.Deserialize<T>(input);
        }

        /// <summary>
        /// Get请求返回json字符串
        /// </summary>
        /// <param name="url"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static string GetJsonStr(string url, Encoding encoding = null)
        {
            string input = HttpGet(url, encoding);
            return input;
        }
        #endregion

        #region Post
        /// <summary>
        /// 构造url的参数ajax的data值
        /// </summary>
        /// <param name="dic"></param>
        /// <returns></returns>
        public static string GetUrlStr(Dictionary<string, string> dic)
        {
            StringBuilder sb = new StringBuilder();
            foreach (var item in dic)
            {
                sb.AppendFormat("{0}={1}&", item.Key, item.Value);
            }
            string urlStr = sb.Remove(sb.Length - 1, 1).ToString();
            return urlStr;
        }

        /// <summary>
        /// 发送post请求
        /// </summary>
        /// <param name="postData"></param>
        /// <param name="postUrl"></param>
        /// <returns></returns>
        public static string PostJsonStr(string postData, string postUrl)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(postUrl);
            byte[] data = Encoding.GetEncoding("gbk").GetBytes(postData);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;
            using (Stream stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string responseString = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")).ReadToEnd();
            return responseString;
        }

        #endregion  
    }

注意引用的命名空间

代码语言:javascript
复制
using AutoO2O.BLL;
using AutoO2O.Common;
using AutoO2O.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Timers;
using System.Web.Mvc;

将请求的结果转化输出给ajax请求

代码语言:javascript
复制
    protected string Write<T>(string callBack, string paramName, object o)
        {
            Newtonsoft.Json.JsonSerializerSettings jSetting = new Newtonsoft.Json.JsonSerializerSettings();
            jSetting.NullValueHandling = NullValueHandling.Ignore;
            if (string.IsNullOrEmpty(callBack) && string.IsNullOrEmpty(paramName))
                return JsonConvert.SerializeObject(o, jSetting);
            else if (!string.IsNullOrEmpty(callBack))
                return callBack + "(" + JsonConvert.SerializeObject(o, jSetting) + ");";
            else
                return "var " + paramName + " = " + JsonConvert.SerializeObject(o, jSetting) + ";";
        }

辅助测试

代码语言:javascript
复制
 public class MyClass
    {
        public string Name { get; set; }
        public string JC { get; set; }

    }
代码语言:javascript
复制
   public string MyTest()
        {
            string callBack = Request["callback"] + "";
            //string ss =GetJsonStr("http://192.168.5.88:8888/test/GetD/24");
            //return Write<MyClass>(callBack, "", ss);
            Dictionary<string, string>dic=new Dictionary<string,string>();
            dic.Add("id","15");
            string param = HttpHelper.GetUrlStr(dic);
            string result = HttpHelper.PostJsonStr(param, "http://192.168.5.88:8888/test/GetD");
            return Write<string>(callBack, "", result);      
        }

静态页面请求

代码语言:javascript
复制
   $.ajax({
            url: 'http://192.168.5.88:8022/test/MyTest',
            dataType: 'jsonp',
            contetType:'text',
            success: function (res) {
                debugger;
            }

        })

调试

显然请求成功

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-04-23 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档