HttpWebRequest和HttpWebRespone使用实例

最近参与了公司的一个和微信平台相关的项目,最近加班加点和第三方调接口。接口走的是http协议,对方返回数据格式为json格式。现在记录下用到的一些知识,以便以后方便查阅。c#真是方便,可以通过JavaScriptSerializer类实现对json数据转化为对象,将对象转化为json串

对方大概提供了两种类型的接口:

一种是直接访问url便可获得数据,一种是要我这边组织json格式的数据再post的过去。

1:

 var request = WebRequest.CreateHttp(MSURI);//实例化HttpWebRequest对象
                request.AllowAutoRedirect = true;//设置请求跟随重定向响应
                request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;//设置请求解压缩的类型
                request.UserAgent = Util.UserAgent_Common;//设置用户客户端信息
                request.Method = "POST";
                //request.ContentType = "application/json";
                var response = request.GetResponse();//生成响应对象
                string content;
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    content = reader.ReadToEnd();
                }
                Trace.WriteLine(content);

2:

            string orderJson = Util.SharedJson.Value.Serialize(order);


            Trace.WriteLine("json发送信息\r\n" + orderJson);
            try
            {
                var request = WebRequest.CreateHttp(MSORDERURI + System.Web.HttpUtility.UrlEncode(orderJson, Encoding.UTF8));
                Trace.WriteLine("请求地址:" + MSORDERURI + System.Web.HttpUtility.UrlEncode(orderJson, Encoding.UTF8));
                request.AllowAutoRedirect = true;
                request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
                request.UserAgent = Util.UserAgent_Common;
                request.Method = "POST";

                //根据接口的要求对post过去的内容设置编码方式
                using (var requestStream = request.GetRequestStream())
                {
                    var jsonContent = new StringContent(orderJson, Encoding.UTF8);
                    request.ContentType = "application/json";
                    jsonContent.CopyToAsync(requestStream).Wait(500);
                }
                var response = request.GetResponse();
                string content;
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    content = reader.ReadToEnd();
                }
                Trace.WriteLine(content);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值