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 = ;//一分钟
request.ReadWriteTimeout = ;//一分钟
request.KeepAlive = false;
byte[] datas = Encoding.UTF8.GetBytes(postData);
request.ContentLength = datas.Length; Stream requestStream = request.GetRequestStream();
requestStream.Write(datas, , datas.Length);
requestStream.Close(); HttpWebResponse response = null;
string responseDatas = string.Empty;
try
{
//多线程中调用 HttpWebRequest 时,需要设置 ServicePointManager.DefaultConnectionLimit 数(默认连接数是 2)。
//当多线程请求时,同时的连接数超过Limit时,GetResponse会抛出 Timeout WebException。
ServicePointManager.DefaultConnectionLimit = ;
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";这句话很重要,服务器的不同接收方式这里一定要标注准确了

上一篇:httpd2.4.6配置文件解释说明


下一篇:scsi线