本文整理汇总了C#中System.Net.HttpWebRequest.AddRange方法的典型用法代码示例。如果您正苦于以下问题:C# HttpWebRequest.AddRange方法的具体用法?C# HttpWebRequest.AddRange怎么用?C# HttpWebRequest.AddRange使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.HttpWebRequest
的用法示例。
在下文中一共展示了HttpWebRequest.AddRange方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: DownloadFile
/// <summary>
/// Download a file from the specified url and copy it to the specified path
/// </summary>
private void DownloadFile(string url, string path, long startPoint)
{
int startingPoint = Convert.ToInt32(startPoint);
try
{
//For using untrusted SSL Certificates
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(OnCheckRemoteCallback);
_Request = (HttpWebRequest)HttpWebRequest.Create(url);
_Request.AddRange(startingPoint);
if (!string.IsNullOrEmpty(LoginUsername))
{
_Request.Credentials = new NetworkCredential(LoginUsername, LoginPassword);
}
else
{
_Request.Credentials = CredentialCache.DefaultCredentials;
}
if (ProxyEnabled)
{
_Request.Proxy = new WebProxy(ProxyURL);
}
_Response = (HttpWebResponse)_Request.GetResponse();
Stream responseSteam = _Response.GetResponseStream();
if (startingPoint == 0)
{
_SaveFileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
}
else
{
_SaveFileStream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
}
int bytesSize;
long fileSize = _Response.ContentLength;
byte[] downloadBuffer = new byte[DEF_PACKET_LENGTH];
OnProgressChanged(new DownloadProgressEventArgs(fileSize, 0, "Starting the download..."));
while ((bytesSize = responseSteam.Read(downloadBuffer, 0, downloadBuffer.Length)) > 0 && !_ExitThread)
{
if (_ExitThread)
{
break;
}
_SaveFileStream.Write(downloadBuffer, 0, bytesSize);
OnProgressChanged(new DownloadProgressEventArgs(_SaveFileStream.Length, fileSize + startingPoint, "Download in progress..."));
}
if (_ExitThread)
{
_SaveFileStream.Close();
_SaveFileStream.Dispose();
OnDownloadCompleted(new DownloadCompleteEventArgs(false, true));
return;
}
OnDownloadCompleted(new DownloadCompleteEventArgs(true, false));
}
catch (Exception ex)
{
OnDownloadError(new DownloadErrorEventArgs(ex, string.Format("Problem downloading and copying file from {0} to {1}.", url, path)));
OnDownloadCompleted(new DownloadCompleteEventArgs(false, false));
}
finally
{
if (_SaveFileStream != null)
{
_SaveFileStream.Close();
_SaveFileStream.Dispose();
}
if (_Response != null)
{
_Response.Close();
}
}
}
示例2: AddRange
private static void AddRange(HttpWebRequest requestToAddUpon, KeyValuePair<string, string> headerPair)
{
var splitted = headerPair.Value.Split('-'); // Split from and to
string part1 = splitted[0];
string specifier = string.Empty;
if (part1.Contains("=")) // range does sometimes have a specification part
{
var splitted2 = splitted[0].Split('=');
specifier = splitted2[0];
part1 = splitted2[1];
}
int fromPoint = Convert.ToInt32(part1);
int toPoint = Convert.ToInt32(splitted[1]);
if (string.IsNullOrEmpty(specifier))
{
requestToAddUpon.AddRange(fromPoint, toPoint);
}
else
{
requestToAddUpon.AddRange(specifier, fromPoint, toPoint);
}
}
示例3: restart
public void restart()
{
Console.Out.WriteLine("restart");
//If file exists, get the pointer of the stream
if (File.Exists(localDir))
{
fs = File.OpenWrite(localDir);
startPos = fs.Length;
fs.Seek(startPos, SeekOrigin.Current);
Console.Out.WriteLine("startPos: " + startPos.ToString());
}
else
{
fs = new FileStream(localDir, FileMode.Create);
startPos = 0;
}
try
{
request = (HttpWebRequest)HttpWebRequest.Create(url);
//if there is an existing file, add range parameters to the request
if (startPos > 0)
{
request.AddRange((int)startPos);
}
responeStream = request.GetResponse().GetResponseStream();
byte[] nBytes = new byte[512];
int nReadSize = 0;
nReadSize = responeStream.Read(nBytes, 0, 512);
while (nReadSize > 0)
{
fs.Write(nBytes, 0, nReadSize);
nReadSize = responeStream.Read(nBytes, 0, 512);
Console.Out.WriteLine(nReadSize.ToString());
}
fs.Close();
responeStream.Close();
}
catch (Exception ex)
{
fs.Close();
responeStream.Close();
Console.Out.WriteLine("restart Exception");
if (reConnectTimer == null)
reConnectTimer = new Timer();
reConnectTimer.Interval = 3000;
reConnectTimer.Elapsed += reConnectTimer_Elapsed;
reConnectTimer.Start();
}
}
示例4: AddHeaders
internal void AddHeaders(HttpWebRequest requestToAddUpon)
{
foreach (var headerPair in Headers)
{
if (!WebHeaderCollection.IsRestricted(headerPair.Key)) // Test if the header is restricted, if not we can just add it
{
requestToAddUpon.Headers.Add(headerPair.Key, headerPair.Value);
}
else
{
switch (headerPair.Key)
{
case "Range":
if (headerPair.Value.Contains("-")) // This part is a bit of a gamble..
{
AddRange(requestToAddUpon, headerPair);
}
else
{
int range = Convert.ToInt32(headerPair.Value);
requestToAddUpon.AddRange(range);
}
break;
case "User-Agent":
requestToAddUpon.UserAgent = headerPair.Value;
break;
default:
throw new ApplicationException("Restricted header was found, but no implementation was made in lib to handle it.");
}
}
}
}
示例5: DocumentFormatReader
public DocumentFormatReader(Uri address, OpenOptions options = null)
{
_request = (HttpWebRequest)WebRequest.Create(address);
if (options != null)
{
if (options.SkipContent)
{
_request.Method = WebRequestMethods.Http.Head;
}
if (options.RangeFrom.HasValue)
{
if (options.RangeTo.HasValue)
_request.AddRange(options.RangeFrom.Value, options.RangeTo.Value);
else
_request.AddRange(options.RangeFrom.Value);
}
}
}
示例6: receive
//接收线程
public void receive()
{
filename = formm.filenamew[threadh];
strUrl = formm.strurl;
ns = null;
nbytes = new byte[512];
nreadsize = 0;
Console.WriteLine("线程" + threadh.ToString() + "开始接收");
if (!File.Exists(filename))
{
fs = new FileStream(filename, System.IO.FileMode.Create);
}
else
{
fs = File.OpenWrite(filename);
DownLoadSize = fs.Length;
formm.DownLoadtotal += DownLoadSize;
formm.filestartw[threadh] += DownLoadSize;
fs.Seek(DownLoadSize, SeekOrigin.Current); //已经存在
}
if (!formm.threadw[threadh])
{
try
{
request = (HttpWebRequest)HttpWebRequest.Create(strUrl);
//接收的起始位置及接收的长度
request.AddRange(formm.filestartw[threadh], formm.filestartw[threadh] + formm.filesizew[threadh]-DownLoadSize);
ns = request.GetResponse().GetResponseStream();//获得接收流
nreadsize = ns.Read(nbytes, 0, 512);
while (nreadsize > 0)
{
fs.Write(nbytes, 0, nreadsize);
nreadsize = ns.Read(nbytes, 0, 512);
formm.DownLoadtotal += 512;
Console.WriteLine("线程" + threadh.ToString() + "正在接收" + formm.DownLoadSpeed.ToString() + "k/s___已经下了" + formm.DownLoadtotal.ToString() + "还剩下" + formm.LeftDownLoadTime.ToString() + "s" + "百分比" + formm.DownLoadPercentage.ToString());
}
fs.Close();
ns.Close();
}
catch (Exception er)
{
Console.WriteLine("123");
fs.Close();
}
}
Console.WriteLine("进程" + threadh.ToString() + "接收完毕!");
formm.threadw[threadh] = true;
}
示例7: receive
public void receive()
{
initiate();
try
{
StartEvent(this, null);
request = (HttpWebRequest)HttpWebRequest.Create(theurl);
request.AddRange(threadManage.fileStart[threadNumber],
threadManage.fileStart[threadNumber] + threadManage.fileSize[threadNumber]);
iostream = request.GetResponse().GetResponseStream();
do
{
if (downloading)
{
nreadsize = iostream.Read(nbytes, 0, 512);
fs.Write(nbytes, 0, nreadsize);
downloadbytes += nreadsize;
}
else
{
threadManage.threadEnd[threadNumber] = true;
return;
}
} while (nreadsize > 0);
fs.Close();
iostream.Close();
}
catch (System.Exception ex)
{
MessageBox.Show("Error in snippet receiving:" + ex.Message);
fs.Close();
}
endreceive();
threadManage.threadEnd[threadNumber] = true;
}
示例8: HttpRequest
public HttpRequest(string method, string url, Dictionary<string, string> headers=null, Dictionary<string, string> query=null, Tuple<long, long> byteRange=null)
{
var uriQuery = query != null && query.Count > 0 ? _add_query(query) : "";
_request = (HttpWebRequest) WebRequest.Create(url + uriQuery);
if (byteRange != null)
_request.AddRange(byteRange.Item1, byteRange.Item2);
Timeout = MillisecondsInOneHour;
if (headers != null)
_add_headers(headers);
_request.Method = method;
}
示例9: CalculateTotalSize
private void CalculateTotalSize(object startpoint)
{
foreach (DataGridViewRow fileRow in fileList.Rows)
{
if ((fileRow.Cells["optional"].Value.ToString() == "0" || update_optional.Checked) && fileRow.Cells["localmd5"].Value.ToString() != fileRow.Cells["md5"].Value.ToString())
{
try
{
// Create a request to the file we are downloading
webRequest = (HttpWebRequest)WebRequest.Create("http://update.srb2.org/files_beta/" + fileRow.Cells["filename"].Value.ToString());
// Set the starting point of the request
webRequest.AddRange(0);
// Set default authentication for retrieving the file
webRequest.Credentials = CredentialCache.DefaultCredentials;
// Retrieve the response from the server
webResponse = (HttpWebResponse)webRequest.GetResponse();
// Ask the server for the file size and store it
Int64 fileSize = webResponse.ContentLength;
TotalSize = TotalSize + fileSize;
}
finally
{
// When the above code has ended, close the streams
webResponse.Close();
}
}
}
doneCalculate = true;
updateList(false);
}
示例10: Download
private void Download(object startpoint)
{
try
{
string filename = Convert.ToString(startpoint);
// Create a request to the file we are downloading
webRequest = (HttpWebRequest)WebRequest.Create("http://update.srb2.org/files_beta/" + downFile);
// Set the starting point of the request
webRequest.AddRange(0);
// Set default authentication for retrieving the file
webRequest.Credentials = CredentialCache.DefaultCredentials;
// Retrieve the response from the server
webResponse = (HttpWebResponse)webRequest.GetResponse();
// Ask the server for the file size and store it
Int64 fileSize = webResponse.ContentLength;
// Open the URL for download
strResponse = webResponse.GetResponseStream();
// Create a new file stream where we will be saving the data (local drive)
strLocal = new FileStream(downFile, FileMode.Create, FileAccess.Write, FileShare.None);
// It will store the current number of bytes we retrieved from the server
int bytesSize = 0;
// A buffer for storing and writing the data retrieved from the server
byte[] downBuffer = new byte[2048];
// Loop through the buffer until the buffer is empty
while ((bytesSize = strResponse.Read(downBuffer, 0, downBuffer.Length)) > 0)
{
// Write the data from the buffer to the local hard drive
strLocal.Write(downBuffer, 0, bytesSize);
// Invoke the method that updates the form's label and progress bar
this.Invoke(new UpdateProgessCallback(this.UpdateProgress), new object[] { strLocal.Length, fileSize });
this.Invoke(new OverallProgessCallback(this.UpdateOverallProgress), new object[] { strLocal.Length });
if (goPause == true)
{
break;
}
}
}
finally
{
// When the above code has ended, close the streams
strResponse.Close();
strLocal.Close();
// And update the row!
downloadStatus = false;
if (downFile == "srb2update.update" && loadedBat != true)
{
MessageBox.Show("The updater will now restart to apply a patch.", "Self Update", MessageBoxButtons.OK);
CreateUpdaterBat();
startinfo.WindowStyle = ProcessWindowStyle.Hidden;
startinfo.FileName = "srb2update.bat";
System.Diagnostics.Process.Start(startinfo);
downloadStatus = false;
Environment.Exit(0);
} else
updateList(false);
}
}
示例11: HandleRangeHeader
private void HandleRangeHeader(HttpWebRequest webrequest)
{
if (!(request is IRangedRequest)) return;
var rangedRequest = (IRangedRequest) request;
if (rangedRequest.RangeFrom != 0 && rangedRequest.RangeTo == 0)
webrequest.AddRange("bytes", rangedRequest.RangeFrom);
else if (rangedRequest.RangeFrom == 0 && rangedRequest.RangeTo != 0)
webrequest.AddRange("bytes", rangedRequest.RangeTo);
else if (rangedRequest.RangeFrom != 0 && rangedRequest.RangeTo != 0)
webrequest.AddRange("bytes", rangedRequest.RangeFrom, rangedRequest.RangeTo);
}
示例12: BeginRequestCallback
private void BeginRequestCallback() {
UnknownSize = true;
BytesDownloaded = 0;
FileSize = 1;
FileDownloading = true;
ma_bBufferStream = new byte[MetabansRequest.INT_BUFFER_SIZE];
try {
m_webRequest = (HttpWebRequest) WebRequest.Create(DownloadSource);
m_webRequest.Method = Method;
if (Range != null) {
m_webRequest.AddRange((int) Range);
}
if (Referrer != null) {
m_webRequest.UserAgent = Referrer;
}
m_webRequest.Headers.Add(System.Net.HttpRequestHeader.AcceptEncoding, "gzip");
try {
m_webRequest.Proxy = null;
}
catch (Exception) {
}
if (RequestContent != null && RequestContent.Length > 0) {
m_webRequest.ContentType = "application/x-www-form-urlencoded";
m_webRequest.ContentLength = RequestContent.Length;
Stream newStream = m_webRequest.GetRequestStream();
// Send the data.
newStream.Write(Encoding.UTF8.GetBytes(RequestContent), 0, RequestContent.Length);
newStream.Close();
}
if (m_webRequest != null) {
IAsyncResult arResult = m_webRequest.BeginGetResponse(new AsyncCallback(ResponseCallback), this);
ThreadPool.RegisterWaitForSingleObject(arResult.AsyncWaitHandle, new WaitOrTimerCallback(RequestTimeoutCallback), this, m_timeout, true);
}
}
catch (Exception e) {
Console.WriteLine(DownloadSource);
Console.WriteLine(e.StackTrace);
if (RequestError != null) {
Error = e.Message;
RequestError(this);
}
}
}
示例13: ReadRequestHeaders
private static int ReadRequestHeaders(StreamReader sr, HttpWebRequest webReq)
{
String httpCmd;
int contentLen = 0;
do
{
httpCmd = sr.ReadLine();
if (String.IsNullOrEmpty(httpCmd))
return contentLen;
String[] header = httpCmd.Split(colonSpaceSplit, 2, StringSplitOptions.None);
switch (header[0].ToLower())
{
case "host":
webReq.Host = header[1];
break;
case "user-agent":
webReq.UserAgent = header[1];
break;
case "accept":
webReq.Accept = header[1];
break;
case "referer":
webReq.Referer = header[1];
break;
case "cookie":
webReq.Headers["Cookie"] = header[1];
break;
case "proxy-connection":
case "connection":
case "keep-alive":
//ignore these
break;
case "content-length":
int.TryParse(header[1], out contentLen);
break;
case "content-type":
webReq.ContentType = header[1];
break;
case "range": //bytes=100-200
var split1 = header[1].Split(equalSplit);
var split2 = split1[1].Split(new char[] { '-' });
webReq.AddRange(int.Parse(split2[0]), int.Parse(split2[1]));
break;
case "if-modified-since":
String[] sb = header[1].Trim().Split(semiSplit);
DateTime d;
if (DateTime.TryParse(sb[0], out d))
webReq.IfModifiedSince = d;
break;
default:
try
{
webReq.Headers.Add(header[0], header[1]);
}
catch (Exception ex)
{
Console.WriteLine(String.Format("Could not add header {0}. Exception message:{1}", header[0], ex.Message));
}
break;
}
} while (!String.IsNullOrWhiteSpace(httpCmd));
return contentLen;
}
示例14: OpenAt
protected void OpenAt(long offset, HttpMethod method)
{
if (offset < 0) {
throw new IOException("Position cannot be negative");
}
if (offset > 0 && method == HttpMethod.HEAD) {
throw new ArgumentException(
"Cannot use a position (seek) with HEAD request");
}
Close();
Dispose();
request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = method.ToString();
if (referrer != null) {
request.Referer = referrer.ToString();
}
request.AllowAutoRedirect = true;
request.Timeout = TIMEOUT * 1000;
request.UserAgent = UserAgent;
if (offset > 0) {
request.AddRange(offset);
}
response = (HttpWebResponse)request.GetResponse();
if (method != HttpMethod.HEAD) {
responseStream = response.GetResponseStream();
if (responseStream == null) {
throw new IOException("Didn't get a response stream");
}
bufferedStream = new BufferedStream(responseStream, BUFFER_SIZE);
}
if (offset > 0 && response.StatusCode != HttpStatusCode.PartialContent) {
throw new IOException(
"Failed to open the http stream at a specific position");
}
if (offset == 0 && response.StatusCode != HttpStatusCode.OK) {
throw new IOException("Failed to open the http stream");
}
logger.InfoFormat("Opened {0} {1} at {2}", method, uri, offset);
}
示例15: ReadRequestHeaders
private static void ReadRequestHeaders(ref List<string> RequestLines, HttpWebRequest WebRequest)
{
for (int i = 1; i < RequestLines.Count; i++)
{
String httpCmd = RequestLines[i];
String[] header = httpCmd.Split(colonSpaceSplit, 2, StringSplitOptions.None);
if (!String.IsNullOrEmpty(header[0].Trim()))
switch (header[0].ToLower())
{
case "accept":
WebRequest.Accept = header[1];
break;
case "accept-encoding":
WebRequest.Headers.Add(header[0], "gzip,deflate,zlib");
break;
case "cookie":
WebRequest.Headers["Cookie"] = header[1];
break;
case "connection":
if (header[1].ToLower() == "keep-alive")
WebRequest.KeepAlive = true;
break;
case "content-length":
int contentLen;
int.TryParse(header[1], out contentLen);
if (contentLen != 0)
WebRequest.ContentLength = contentLen;
break;
case "content-type":
WebRequest.ContentType = header[1];
break;
case "expect":
if (header[1].ToLower() == "100-continue")
WebRequest.ServicePoint.Expect100Continue = true;
else
WebRequest.Expect = header[1];
break;
case "host":
WebRequest.Host = header[1];
break;
case "if-modified-since":
String[] sb = header[1].Trim().Split(semiSplit);
DateTime d;
if (DateTime.TryParse(sb[0], out d))
WebRequest.IfModifiedSince = d;
break;
case "proxy-connection":
break;
case "range":
var startEnd = header[1].Replace(Environment.NewLine, "").Remove(0, 6).Split('-');
if (startEnd.Length > 1) { if (!String.IsNullOrEmpty(startEnd[1])) WebRequest.AddRange(int.Parse(startEnd[0]), int.Parse(startEnd[1])); else WebRequest.AddRange(int.Parse(startEnd[0])); }
else
WebRequest.AddRange(int.Parse(startEnd[0]));
break;
case "referer":
WebRequest.Referer = header[1];
break;
case "user-agent":
WebRequest.UserAgent = header[1];
break;
case "transfer-encoding":
if (header[1].ToLower() == "chunked")
WebRequest.SendChunked = true;
else
WebRequest.SendChunked = false;
break;
case "upgrade":
if (header[1].ToLower() == "http/1.1")
WebRequest.Headers.Add(header[0], header[1]);
break;
default:
if (header.Length > 0)
WebRequest.Headers.Add(header[0], header[1]);
else
WebRequest.Headers.Add(header[0], "");
break;
}
}
}