天天看點

C# HttpWebRequest\HttpWebResponse\WebClient發送請求解析json資料

在 ASP.NET Core 中使用 IHttpClientFactory 發出 HTTP 請求

*

*

======================================================================================================================================
/// <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.ContentType = "application/json";
        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 = data.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 methodUrl = string.Empty;
        public string postStr = null;

        public MyHttpClient(String methodUrl)
        {
            this.methodUrl = methodUrl;
        }

        public MyHttpClient(String methodUrl, String postStr)
        {
            ///this.methodUrl = ConfigurationManager.AppSettings["ApiFrontEnd"];///http://192.168.1.6:8098/Signin/LoginApi
            ///this.postStr = postStr;

            this.methodUrl = methodUrl;
            this.postStr = postStr;
        }

        /// <summary>
        /// GET Method
        /// </summary>
        /// <returns></returns>
        public String ExecuteGet()
        {
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(this.methodUrl);
            myRequest.Method = "GET";

            HttpWebResponse myResponse = null;
            try
            {
                myResponse = (HttpWebResponse)myRequest.GetResponse();
                StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                string content = reader.ReadToEnd();
                return content;
            }
            //異常請求
            catch (WebException e)
            {
                myResponse = (HttpWebResponse)e.Response;
                using (Stream errData = myResponse.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(errData))
                    {
                        string text = reader.ReadToEnd();

                        return text;
                    }
                }
            }
        }

        /// <summary>
        /// POST Method
        /// </summary>
        /// <returns></returns>
        public string ExecutePost()
        {
            string content = string.Empty;

            Random rd = new Random();
            int rd_i = rd.Next();
            String nonce = Convert.ToString(rd_i);
            String timestamp = Convert.ToString(ConvertDateTimeInt(DateTime.Now));
            String signature = GetHash(this.appSecret + nonce + timestamp);

            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(this.methodUrl);
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                //request.ContentType = "application/json";
                request.Headers.Add("Nonce", nonce);
                request.Headers.Add("Timestamp", Convert.ToString(StringProc.ConvertDateTimeInt(DateTime.Now)));
                request.Headers.Add("Signature", signature);
                request.ReadWriteTimeout = 30 * 1000;

                byte[] data = Encoding.UTF8.GetBytes(postStr);
                request.ContentLength = data.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()
        {
            #region DoGet

            string getResultJson = this.DoGet(url);
            HttpClientResult customerResult = (HttpClientResult)JsonConvert.DeserializeObject(getResultJson, typeof(HttpClientResult));

            #endregion

            #region DoPost

            string name = Request.Form["UserName"];
            string password = Request.Form["Password"];

            Dictionary<String, String> dicList = new Dictionary<String, String>();
            dicList.Add("UserName", name);
            dicList.Add("Password", password);
            string postStr = StringProc.buildQueryStr(dicList);

            string postResultJson = this.DoPost(url, postStr);
            HttpClientResult userResult = (HttpClientResult)JsonConvert.DeserializeObject(postResultJson, typeof(HttpClientResult));

            #endregion

            return View();
        }

        /// <summary>
        /// GET Method
        /// </summary>
        /// <param name="portraitUri">url位址</param>
        /// <returns></returns>
        private String DoGet(string portraitUri)
        {
            MyHttpClient client = new MyHttpClient(portraitUri);
            return client.ExecuteGet();
        }

        /// <summary>
        /// POST Method
        /// </summary>
        /// <param name="portraitUri">url位址</param>
        /// <param name="postStr">請求參數</param>
        /// <returns></returns>
        private String DoPost(string portraitUri, string postStr)
        {
            MyHttpClient client = new MyHttpClient(portraitUri, postStr);
            return client.ExecutePost();
        }

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

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

HttpClient

var responseString = string.Empty;
using (var client = new HttpClient())
{
    var values = new Dictionary<string, string>
    {
        { "apikey", apiKey },
        { "mobile", phoneNumber },
        { "text", smsMessage }
    };
    
    var content = new FormUrlEncodedContent(values);
    var response = await client.PostAsync(url, content);
    responseString = await response.Content.ReadAsStringAsync();
}
           

.net framework 3.5 版本,遇見“基礎連接配接已關閉”的問題,嘗試如下方法:

ServicePointManager.SecurityProtocol = (SecurityProtocolType)768;

ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;

微軟官方文檔說明:https://docs.microsoft.com/zh-cn/dotnet/api/system.net.securityprotocoltype?view=netframework-4.7.2

C# HttpWebRequest\HttpWebResponse\WebClient發送請求解析json資料

繼續閱讀