C# HttpWebRequest\HttpWebResponse\WebClient发送请求解析json数据

======================================================================================================================================
/// <summary>
/// 日期:2016-2-4
/// 备注:bug已修改,可以使用
/// </summary>
public static void Method1()
{
    try
    {
        string domain = "http://192.168.1.6:8098/";
        string url = domain + "/Signin/LoginApi";
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.ReadWriteTimeout = 30 * 1000;

        ///添加参数
        Dictionary<String, String> dicList = new Dictionary<String, String>();
        dicList.Add("UserName", "[email protected]");
        dicList.Add("Password", "000000");
        String postStr = buildQueryStr(dicList);
        byte[] data = Encoding.UTF8.GetBytes(postStr);

        request.ContentLength = postStr.Length;

        Stream myRequestStream = request.GetRequestStream();
        myRequestStream.Write(data, 0, data.Length);
        myRequestStream.Close();

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        StreamReader myStreamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
        var retString = myStreamReader.ReadToEnd();
        myStreamReader.Close();
    }
    catch (Exception ex)
    {
        log.Info("Entered ItemHierarchyController - Initialize");
        log.Error(ex.Message);
    }
}
======================================================================================================================================


升级版本,提取到帮助类,封装对象


using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Net;
using System.Text;
using System.Web;

namespace CMS.Common
{
    public class MyHttpClient
    {
        public string server_addr = string.Empty;
        public string postStr = null;

        public MyHttpClient(string postStr)
        {
            server_addr = ConfigurationManager.AppSettings["ApiFrontEnd"];///http://192.168.1.6:8098/Signin/LoginApi
            this.postStr = postStr;
        }

        public string ExecutePost()
        {
            string content = string.Empty;
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(server_addr);
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.Headers.Add("Timestamp", Convert.ToString(StringProc.ConvertDateTimeInt(DateTime.Now)));
                request.ReadWriteTimeout = 30 * 1000;

                byte[] data = Encoding.UTF8.GetBytes(postStr);
                request.ContentLength = postStr.Length;

                Stream myRequestStream = request.GetRequestStream();

                myRequestStream.Write(data, 0, data.Length);
                myRequestStream.Close();

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                StreamReader myStreamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                content = myStreamReader.ReadToEnd();
                myStreamReader.Close();
            }
            catch (Exception ex)
            {
            }
            return content;
        }
    }

    public class StringProc
    {
        public static String buildQueryStr(Dictionary<String, String> dicList)
        {
            String postStr = "";

            foreach (var item in dicList)
            {
                postStr += item.Key + "=" + HttpUtility.UrlEncode(item.Value, Encoding.UTF8) + "&";
            }
            postStr = postStr.Substring(0, postStr.LastIndexOf('&'));
            return postStr;
        }

        public static int ConvertDateTimeInt(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return (int)(time - startTime).TotalSeconds;
        }
    }
}

前端调用


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CMS.Common;
using Newtonsoft.Json;

namespace Medicine.Web.Controllers
{
    public class DefaultController : Controller
    {
        public ActionResult Index()
        {
            string name = Request.Form["UserName"];
            string password = Request.Form["Password"];
            string jsonString = HttpClientLogin(name, password);

            HttpClientResult result = (HttpClientResult)JsonConvert.DeserializeObject(jsonString, typeof(HttpClientResult));
            return View();
        }

        private string HttpClientLogin(string username, string password)
        {
            Dictionary<String, String> dicList = new Dictionary<String, String>();
            dicList.Add("UserName", username);
            dicList.Add("Password", password);
            String postStr = StringProc.buildQueryStr(dicList);
            MyHttpClient client = new MyHttpClient(postStr);
            string result = client.ExecutePost();
            return result;
        }

        public class HttpClientResult
        {
            public string UserName { get; set; }

            public bool Success { get; set; }
        }
    }
}


你可能感兴趣的:(webclient,HttpWebResponse,WebRequest)