zoukankan      html  css  js  c++  java
  • 【C#网络基础】C# get post请求

    using KTCommon.Helper;
    using KTCommon.LOG;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace KTCommon.HTTP
    {
        public class KTHttpRequest
        {
            #region GET请求
    
            /// <summary>
            /// GET请求
            /// </summary>
            /// <param name="nUrl"></param>
            /// <param name="nCacheSecond"></param>
            /// <returns></returns>
            public static string _Get(string nUrl, int nCacheSecond = 0)
            {
                try
                {
                    string cacheKey = "";
                    TraceLog.m_Trace.Trace("_Get Request Url=" + nUrl);
    
                    if (nCacheSecond > 0)
                    {
                        if (nUrl.Contains("&signature="))
                        {
                            string temp = nUrl.Substring(0, nUrl.IndexOf("&signature="));
                            cacheKey = MyMD5Helper.GetMD532(temp).ToUpper();
                        }
                        else
                        {
                            cacheKey = MyMD5Helper.GetMD532(nUrl).ToUpper();
                        }
                        
                        var cache = CacheHelper.Get(cacheKey);
                        if (null != cache)
                        {
                            TraceLog.m_Trace.Trace(cacheKey + " read cache...");
                            return cache as string;
                        }
                    }
    
                    string htmltext = "";
                    HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(nUrl);
    
                    // 头信息
                    myRequest.Headers.Add("Cache-Control", "no-cache");
                    myRequest.Method = "GET";
    
                    myRequest.ContentType = "text/plain";
                    // 发送的数据信息 
                    myRequest.Timeout = 15 * 1000;
    
                    HttpWebResponse response = (HttpWebResponse)myRequest.GetResponse();
                    Stream responseStream = response.GetResponseStream();
                    StreamReader sr = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
                    htmltext = sr.ReadToEnd();
                    sr.Close();
                    sr.Dispose();
                    responseStream.Close();
                    TraceLog.m_Trace.Trace("_Get htmltext=" + htmltext);
    
                    if (nCacheSecond > 0 && htmltext.StartsWith("{"code":0,"))
                    {
                        TraceLog.m_Trace.Trace(cacheKey + " wrrite cache...");
                        CacheHelper.Insert(cacheKey, htmltext, nCacheSecond);
                    }
    
                    return htmltext;
                }
                catch (Exception ex)
                {
                    TraceLog.m_Trace.Trace("_Get Exception=" + ex);
                    return "";
                }
    
            }
    
            #endregion
    
            #region POST请求
    
            /// <summary>
            /// POST请求
            /// </summary>
            /// <param name="nUrl"></param>
            /// <param name="nMethodName"></param>
            /// <param name="nPostData"></param>
            /// <returns></returns>
            public static string _Post(string nUrl, string nMethodName, object nPostData, bool IsCache = false)
            {
    #if DEBUG
                //urlAddress = "http://localhost/airwaykeeper/v1/API/API2WShare.aspx";
                //strMethodName = "_GetShareInfoByUID";
                //strRequest = File.ReadAllText("d:\request.txt", Encoding.UTF8);
    #endif
                string htmltext = "";
                string cacheKey = "";
                Byte[] bSend = null;
                try
                {
                    string postData = Newtonsoft.Json.JsonConvert.SerializeObject(nPostData);
                    TraceLog.m_Trace.Trace(nMethodName + " RequestUrl=" + nUrl);
                    TraceLog.m_Trace.Trace(nMethodName + " PostData=" + postData);
    
                    //缓存
                    if (IsCache)
                    {
                        cacheKey = nMethodName + "-" + MyMD5Helper.GetMD532(nUrl + nMethodName + postData).ToUpper();
                        var cache = CacheHelper.Get(cacheKey);
                        if (null != cache)
                        {
                            TraceLog.m_Trace.Trace(cacheKey + " read cache...");
                            return cache as string;
                        }
                    }
    
                    HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(nUrl);
    
                    // 头信息
                    myRequest.Headers.Add("Cache-Control", "no-cache");
                    myRequest.Headers.Add("MethodName", nMethodName);
                    myRequest.Method = "POST";
    
                    myRequest.ContentType = "application/json";
                    // 发送的数据信息 
                    bSend = Encoding.UTF8.GetBytes(postData);
                    myRequest.ContentLength = bSend.Length;
                    myRequest.Timeout = 60 * 1000;
    
                    // 发送数据 
                    Stream newStream = myRequest.GetRequestStream();
                    newStream.Write(bSend, 0, bSend.Length);
                    newStream.Close();
    
                    HttpWebResponse response = (HttpWebResponse)myRequest.GetResponse();
                    Stream responseStream = response.GetResponseStream();
                    StreamReader sr = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
                    htmltext = sr.ReadToEnd();
                    sr.Close();
                    sr.Dispose();
                    responseStream.Close();
                }
                catch (Exception ex)
                {
                    TraceLog.m_Trace.Trace(nMethodName + " Exception=" + ex.ToString());
                    return new BaseResponse(ex.Message).ToString();
                }
                TraceLog.m_Trace.Trace(nMethodName + " ResponseJson=" + htmltext);
    
                //缓存
                if (IsCache)
                {
                    if (htmltext.Contains("IsSuccess":true,"))
                    {
                        TraceLog.m_Trace.Trace(cacheKey + " wrrite cache...");
                        CacheHelper.Max(cacheKey, htmltext);
                    }
                }
    
                return htmltext;
            }
    
            #endregion
        }
    
        public class BaseResponse
        {
            public BaseResponse(string tmp)
            {
    
            }
    
            public override string ToString()
            {
                return "";
            }
        }
    }
  • 相关阅读:
    20155309 《Java程序设计》实验三(Java面向对象程序设计)实验报告
    2016-2017-2 20155309南皓芯《java程序设计》第十周学习总结
    2015309南皓芯实验二 Java面向对象程序设计
    2016-2017-2 20155309南皓芯《java程序设计》第九周学习总结
    2016-2017-2 20155309 南皓芯《java程序设计》第八周学习总结
    2015309南皓芯《Java程序设计》实验一(Java开发环境的熟悉)实验报告
    2016-2017-2 20155309南皓芯《java程序设计》第七周学习总结
    2016-2017-2 20155309南皓芯java第五周学习总结
    20155304 2016-2017-2 《Java程序设计》第六周学习总结
    20155304 2016-2017-2 《Java程序设计》第五周学习总结
  • 原文地址:https://www.cnblogs.com/jhli/p/5912148.html
Copyright © 2011-2022 走看看