• C#模拟HTTP请求并发送二进制


    public static String Submit(String methodName)
    {
        string postData = "this is post data";//请求的数据,后面转换成二进制请求
    
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(URL));
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.Timeout = 60000;//一分钟
        request.ReadWriteTimeout = 60000;//一分钟
        request.KeepAlive = false;
        byte[] datas = Encoding.UTF8.GetBytes(postData);
        request.ContentLength = datas.Length;
    
        Stream requestStream = request.GetRequestStream();
        requestStream.Write(datas, 0, datas.Length);
        requestStream.Close();
    
        HttpWebResponse response = null;
        string responseDatas = string.Empty;
        try
        {
            //多线程中调用 HttpWebRequest 时,需要设置 ServicePointManager.DefaultConnectionLimit 数(默认连接数是 2)。 
            //当多线程请求时,同时的连接数超过Limit时,GetResponse会抛出 Timeout WebException。
            ServicePointManager.DefaultConnectionLimit = 100;
            response = (HttpWebResponse)request.GetResponse();
            Stream streamResponse = response.GetResponseStream();
            if (streamResponse != null)
            {
                using (StreamReader sr = new StreamReader(streamResponse))
                {
                    responseDatas = sr.ReadToEnd();
                }
            }
            else
            {
                responseDatas = "{"Code":-1,"Data":"[]"}";
            }
        }
        finally
        {
            if (response != null)
            {
                try
                {
                    response.Close();
                }
                catch
                {
                    request.Abort();
                }
            }
        }
        
        return responseDatas;
    }

     request.ContentType = "application/x-www-form-urlencoded";这句话很重要,服务器的不同接收方式这里一定要标注准确了

  • 相关阅读:
    Discuz! 的编码规范
    Golang 并发编程指南
    Hyrum's Law
    从数组中将变量导入到当前的符号表
    map[interface {}]interface {} yaml文件解码
    迪基福勒检验
    约定式路由
    use of internal package github.com/gokratos/kratos/v2/internal/httputil not allowed
    See https://v8.dev/blog/mathrandom for details.
    Cast a value as a certain type
  • 原文地址:https://www.cnblogs.com/duanjt/p/7851204.html
Copyright © 2020-2023  润新知