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

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

 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  
    }

注意引用的命名空间

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请求

    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) + ";";
        }

辅助测试

 public class MyClass
    {
        public string Name { get; set; }
        public string JC { get; set; }

    }
   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);      
        }

静态页面请求

   $.ajax({
            url: 'http://192.168.5.88:8022/test/MyTest',
            dataType: 'jsonp',
            contetType:'text',
            success: function (res) {
                debugger;
            }

        })

调试

显然请求成功

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏王磊的博客

Net连接mysql的公共Helper类MySqlHelper.cs带MySql.Data.dll下载

MySqlHelper.cs代码如下: using System; using System.Collections.Generic; using System...

5269
来自专栏Pythonista

Golang之实现一个负载均衡算法(随机,轮询)

2583
来自专栏草根专栏

.NET Core 网络数据采集 -- 使用AngleSharp做html解析

3500
来自专栏张善友的专栏

发布一个日期选择控件(ASPNET2.0)

The Coolest DHTML Calendar,这是一个在GPL下发布的JS日历程序,具有极高的可配置性,包括外观样式、显示格式、显示内容等等。默认程序...

2539
来自专栏王磊的博客

HttpWebRequest采集读取网站挂载Cookie的通用方法

Asp.net 版本 HttpWebRequest采集时添加:httpWebRequest.CookieContainer = new CookieContai...

2915
来自专栏c#开发者

asp.net回调javascript

using System; using System.Collections; using System.IO; using System.Text; ...

3215
来自专栏c#开发者

让web api 4.5支持Jquery.getJson(url,handle)跨域访问

代码片段,google了半天,找到的都是4.5 rc,或之前版本的代码,发现都不能用,正式版后有些方法做了修改。我重新修改一下分享给大家 public stat...

2755
来自专栏个人随笔

C#编写影院售票系统(A project with a higher amount of gold )(2:相关代码)

此篇文章为项目代码,,,需要项目需求 ,思路分析与窗体效果请访问:http://www.cnblogs.com/lsy131479/p/8367304.html...

3175
来自专栏c#开发者

Debatching(Splitting) XML Message in Orchestration using DefaultPipeline - BizTalk 2010

Debatching(Splitting) XML Message in Orchestration using DefaultPipeline - BizTa...

3469
来自专栏菩提树下的杨过

C#:DataTable映射成Model

这是数据库开发中经常遇到的问题,当然,这可以用现成的ORM框架来解决,但有些时候,如果DataSet/DataTable是第三方接口返回的,ORM就不方便了,还...

21610

扫码关注云+社区