httpclient source code by csharp
private HttpWebRequest CreateRequest()
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.AllowAutoRedirect = false;
req.CookieContainer = new CookieContainer();
req.Headers.Add("Accept-Language", defaultLanguage);
req.Accept = accept;
req.UserAgent = userAgent;
req.KeepAlive = false;
if (context.Cookies != null)
req.CookieContainer.Add(context.Cookies);
if (!string.IsNullOrEmpty(context.Referer))
req.Referer = context.Referer;
if (verb == HttpVerb.HEAD)
{
req.Method = "HEAD";
return req;
}
if (postingData.Count > 0 || files.Count > 0)
verb = HttpVerb.POST;
if (verb == HttpVerb.POST)
{
req.Method = "POST";
MemoryStream memoryStream = new MemoryStream();
StreamWriter writer = new StreamWriter(memoryStream);
if (files.Count > 0)
{
string newLine = "\r\n";
string boundary = Guid.NewGuid().ToString().Replace("-", "");
req.ContentType = "multipart/form-data; boundary=" boundary;
foreach (string key in postingData.Keys)
{
writer.Write("--" boundary newLine);
writer.Write("Content-Disposition: form-data; name=\"{0}\"{1}{1}", key, newLine);
writer.Write(postingData[key] newLine);
}
foreach (HttpUploadingFile file in files)
{
writer.Write("--" boundary newLine);
writer.Write(
"Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"{2}",
file.FieldName,
file.FileName,
newLine
);
writer.Write("Content-Type: application/octet-stream" newLine newLine);
writer.Flush();
memoryStream.Write(file.Data, 0, file.Data.Length);
writer.Write(newLine);
writer.Write("--" boundary newLine);
}
}
else
{
req.ContentType = "application/x-www-form-urlencoded";
StringBuilder sb = new StringBuilder();
foreach (string key in postingData.Keys)
{
sb.AppendFormat("{0}={1}&", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(postingData[key]));
}
if (sb.Length > 0)
sb.Length--;
writer.Write(sb.ToString());
}
writer.Flush();
using (Stream stream = req.GetRequestStream())
{
memoryStream.WriteTo(stream);
}
}
if (startPoint != 0 && endPoint != 0)
req.AddRange(startPoint, endPoint);
else if (startPoint != 0 && endPoint == 0)
req.AddRange(startPoint);
return req;
}
评论