zoukankan      html  css  js  c++  java
  • 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";这句话很重要,服务器的不同接收方式这里一定要标注准确了

  • 相关阅读:
    [AH2017/HNOI2017]礼物
    [八省联考2018]林克卡特树lct
    [洛谷P4847]银河英雄传说V2
    [洛谷P4999]烦人的数学作业
    [洛谷P4171][JSOI2010]满汉全席
    [CF785E]Anton and Permutation
    [洛谷P2511][HAOI2008]木棍分割
    [洛谷P4430]小猴打架
    [UVA307]小木棍 Sticks
    [LOJ #6433]「PKUSC2018」最大前缀和
  • 原文地址:https://www.cnblogs.com/duanjt/p/7851204.html
Copyright © 2011-2022 走看看