码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2017-11-17 14:53:49      阅读:252      评论:0      收藏:0      [点我收藏+]

标签:read   encode   abort   pre   form   amr   manage   epo   stat   

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;
}

 

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

标签:read   encode   abort   pre   form   amr   manage   epo   stat   

原文地址:http://www.cnblogs.com/duanjt/p/7851204.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!