asp.net页面访问http接口,发送JSON并解析JSON结果.

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace WebApplication3
{
    //返回的JSON对象结构对象
    public class errormsg
    {
        public string resultCode { get; set; }
        public string message { get; set; }
    }

    public partial class author : System.Web.UI.Page
    {
        public string buffer = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            var strUrl = "XXXXX"; //接口URL
            //json字典
            IDictionary<string, string> parameters = new Dictionary<string, string>();
            parameters.Add("name", code);
            parameters.Add("pswd", code);
            //调用方法
            string strResult = this.iPost(strUrl, parameters, 5000); 
            
            try
            {
            	//解码json
                var pp = JsonConvert.DeserializeObject<errormsg>(strResult);                
                if (pp.resultCode != "0")
                {
                    Response.Write("login fail:"+buffer);
                    Response.End();
                }
            }catch(Exception ex){}
        }

//接口访问方法
        private string iPost(string strUrl, IDictionary<string, string> parameters, int timeout)
        {
            try
            { 
                HttpWebRequest request = WebRequest.Create(strUrl) as HttpWebRequest;
                request.ServicePoint.Expect100Continue = false;
                request.ServicePoint.UseNagleAlgorithm = false; //是否使用 Nagle 不使用 提高效率
                                                                //request.AllowWriteStreamBuffering = false; //数据是否缓冲 false 提高效率
                request.Method = "POST";
                request.ContentType = "application/json";//没效果
                request.Accept = "application/json";   //该编码有效,可解决乱码问题 
                request.Timeout = timeout;
                
                Encoding requestEncoding = Encoding.GetEncoding("UTF-8");
                //如果需要POST数据  
                if (!(parameters == null || parameters.Count == 0))
                {
                    buffer=JsonConvert.SerializeObject(parameters);                     
                    byte[] data = requestEncoding.GetBytes(buffer);
                    using (Stream stream = request.GetRequestStream())
                    {
                        stream.Write(data, 0, data.Length);
                    }
                }

                //获取响应,并设置响应编码
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                string encoding = response.ContentEncoding;
                if (encoding == null || encoding.Length < 1)
                {
                    encoding = "UTF-8"; //默认编码
                }
                //读取响应流
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
                string returnData = reader.ReadToEnd();
                reader.Dispose();
                response.Close();
                return returnData;
            }
            catch (Exception ex)
            { 
                return "error:<br> send:"+ buffer +";<br>"+ex.ToString();
            } 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值