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 "";
            }
        }
    }
  • 相关阅读:
    乌龟棋 (codevs 1068)题解
    全排列 (codevs 1294)题解
    最小伤害 题解
    编码问题 题解
    基础DAY3-运算符 逻辑运算符 if elif
    图解算法——合并k个排序列表(Merge k Sorted Lists)
    算法图解——组合求和( Combination Sum)
    make命令使用 & makefile编写详解
    并发工具CountDownLatch源码分析
    线程局部变量ThreadLocal实现原理
  • 原文地址:https://www.cnblogs.com/jhli/p/5912148.html
Copyright © 2011-2022 走看看