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

  • 相关阅读:
    月亮的背后
    2007经典妙语100句
    2007经典妙语100句
    VS C++ 2005的预生成事件及设置
    user case VS. user story
    如何用正确的方法来写出质量好的软件的75条体会
    用 Lucene 加速 Web 搜索应用程序的开发
    巾帼不让须眉——女生做运维 interesting topic
    ebean
    Download the 2.0.0 Release of the Scala IDE for Eclipse Scala IDE for Eclipse
  • 原文地址:https://www.cnblogs.com/duanjt/p/7851204.html
Copyright © 2011-2022 走看看