Here are the examples of the csharp api System.Net.HttpWebResponse.GetResponseStream() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1154 Examples
19
View Source File : GoPhishIntegration.cs
License : GNU General Public License v3.0
Project Creator : 0dteam
License : GNU General Public License v3.0
Project Creator : 0dteam
public static string sendReportNotificationToServer(string reportURL)
{
ServicePointManager.SecurityProtocol = Tls12;
try
{
var request = (HttpWebRequest)WebRequest.Create(reportURL);
var response = (HttpWebResponse)request.GetResponse();
string html = new StreamReader(response.GetResponseStream()).ReadToEnd();
return "OK";
}
catch (System.Exception exc)
{
return "ERROR"; // "GoPhish Listener is not responding or there is no Internet connection."
}
}
19
View Source File : HttpUtil.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
void EndResponse(IAsyncResult ar)
{
StateObject state = ar.AsyncState as StateObject;
try
{
HttpWebResponse webResponse = state.HttpWebRequest.EndGetResponse(ar) as HttpWebResponse;
state.ResponseInfo.StatusCode = webResponse.StatusCode;
state.ResponseInfo.Headers = new WebHeaderCollection();
foreach (string key in webResponse.Headers.AllKeys)
{
state.ResponseInfo.Headers.Add(key, webResponse.Headers[key]);
}
state.ReadStream = webResponse.GetResponseStream();
state.ReadStream.BeginRead(state.Buffer, 0, state.Buffer.Length, ReadCallBack, state);
}
catch (Exception ex)
{
HandException(ex, state);
}
}
19
View Source File : HttpClient.cs
License : GNU Affero General Public License v3.0
Project Creator : 3drepo
License : GNU Affero General Public License v3.0
Project Creator : 3drepo
protected T_out HttpPostJson<T_in, T_out>(string uri, T_in data)
{
AppendApiKey(ref uri);
// put together the json object with the login form data
string parameters = JsonMapper.ToJson(data);
byte[] postDataBuffer = Encoding.UTF8.GetBytes(parameters);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Proxy = proxy;
request.Method = "POST";
request.ContentType = "application/json;charset=UTF-8";
request.ContentLength = postDataBuffer.Length;
//request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
request.ReadWriteTimeout = timeout_ms;
request.Timeout = timeout_ms;
request.CookieContainer = cookies;
Console.WriteLine("POST " + uri + " data: " + parameters);
Stream postDataStream = request.GetRequestStream();
postDataStream.Write(postDataBuffer, 0, postDataBuffer.Length);
postDataStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader responseReader = new StreamReader(responseStream);
string responseData = responseReader.ReadToEnd();
Cookie responseCookie = response.Cookies[0];
string responseDomain = responseCookie.Domain;
// Only replacedume one cookie per domain
if (!cookieDict.ContainsKey(responseDomain))
{
cookieDict.Add(responseCookie.Domain, responseCookie);
responseCookie.Domain = "." + responseCookie.Domain;
}
Uri myUri = new Uri(uri);
foreach (KeyValuePair<string, Cookie> entry in cookieDict)
{
int uriHostLength = myUri.Host.Length;
if (myUri.Host.Substring(uriHostLength - responseDomain.Length, responseDomain.Length) == entry.Key)
{
cookies.Add(myUri, entry.Value);
}
}
return JsonMapper.ToObject<T_out>(responseData);
}
19
View Source File : HttpClient.cs
License : GNU Affero General Public License v3.0
Project Creator : 3drepo
License : GNU Affero General Public License v3.0
Project Creator : 3drepo
protected T HttpGetJson<T>(string uri, int tries = 1)
{
AppendApiKey(ref uri);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Proxy = proxy;
request.Method = "GET";
request.Accept = "application/json";
//request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
request.ReadWriteTimeout = timeout_ms;
request.Timeout = timeout_ms;
request.CookieContainer = cookies;
Console.WriteLine("GET " + uri + " TRY: " + tries);
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader responseReader = new StreamReader(responseStream);
string responseData = responseReader.ReadToEnd();
JsonMapper.RegisterImporter<Double, Single>((Double value) =>
{
return (Single)value;
});
return JsonMapper.ToObject<T>(responseData);
}
catch (WebException)
{
if (--tries == 0)
throw;
return HttpGetJson<T>(uri, tries);
}
}
19
View Source File : HttpClient.cs
License : GNU Affero General Public License v3.0
Project Creator : 3drepo
License : GNU Affero General Public License v3.0
Project Creator : 3drepo
protected virtual Stream HttpGetURI(string uri, int tries = 1)
{
AppendApiKey(ref uri);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Proxy = proxy;
request.Method = "GET";
//request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
request.ReadWriteTimeout = timeout_ms;
request.Timeout = timeout_ms;
request.CookieContainer = cookies;
Console.WriteLine("GET " + uri + " TRY: " + tries);
try
{
MemoryStream memStream;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
memStream = new MemoryStream();
byte[] buffer = new byte[1024];
int byteCount;
int total = 0;
var ns = response.GetResponseStream();
do
{
byteCount = ns.Read(buffer, 0, buffer.Length);
memStream.Write(buffer, 0, byteCount);
total += byteCount;
} while (byteCount > 0);
request.Abort();
}
return memStream;
}
catch (WebException)
{
if (--tries == 0)
throw;
return HttpGetURI(uri, tries);
}
}
19
View Source File : DownloadFile.cs
License : MIT License
Project Creator : 404Lcc
License : MIT License
Project Creator : 404Lcc
public bool Downloading()
{
if (File.Exists(downloadData.path))
{
currentSize = downloadData.size;
return true;
}
long position = 0;
string tempPath = downloadData.path + ".temp";
if (File.Exists(tempPath))
{
using (FileStream fileStream = new FileStream(tempPath, FileMode.Open, FileAccess.Write, FileShare.ReadWrite))
{
position = fileStream.Length;
fileStream.Seek(position, SeekOrigin.Current);
if (position == downloadData.size)
{
if (File.Exists(downloadData.path))
{
File.Delete(downloadData.path);
}
File.Move(tempPath, downloadData.path);
currentSize = position;
return true;
}
}
}
else
{
PathUtil.GetPath(PathType.PersistentDataPath, Path.GetDirectoryName(downloadData.path));
using (FileStream fileStream = new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
{
HttpWebRequest httpWebRequest = null;
HttpWebResponse httpWebResponse = null;
try
{
httpWebRequest = (HttpWebRequest)WebRequest.Create(downloadData.url);
httpWebRequest.ReadWriteTimeout = readWriteTimeout;
httpWebRequest.Timeout = timeout;
if (position > 0)
{
httpWebRequest.AddRange((int)position);
}
httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (Stream stream = httpWebResponse.GetResponseStream())
{
stream.ReadTimeout = timeout;
long currentSize = position;
byte[] bytes = new byte[fileReadLength];
int readSize = stream.Read(bytes, 0, fileReadLength);
while (readSize > 0)
{
fileStream.Write(bytes, 0, readSize);
currentSize += readSize;
if (currentSize == downloadData.size)
{
if (File.Exists(downloadData.path))
{
File.Delete(downloadData.path);
}
File.Move(tempPath, downloadData.path);
}
this.currentSize = currentSize;
readSize = stream.Read(bytes, 0, fileReadLength);
}
}
}
catch
{
if (File.Exists(tempPath))
{
File.Delete(tempPath);
}
if (File.Exists(downloadData.path))
{
File.Delete(downloadData.path);
}
state = DownloadState.Error;
error = "文件下载失败";
}
finally
{
if (httpWebRequest != null)
{
httpWebRequest.Abort();
httpWebRequest = null;
}
if (httpWebResponse != null)
{
httpWebResponse.Dispose();
httpWebResponse = null;
}
}
}
}
if (state == DownloadState.Error)
{
return false;
}
return true;
}
19
View Source File : Utility.Http.cs
License : MIT License
Project Creator : 7Bytes-Studio
License : MIT License
Project Creator : 7Bytes-Studio
public static string Post(string Url, string postDataStr, CookieContainer cookieContainer = null)
{
cookieContainer = cookieContainer ?? new CookieContainer();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
request.CookieContainer = cookieContainer;
Stream myRequestStream = request.GetRequestStream();
StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
myStreamWriter.Write(postDataStr);
myStreamWriter.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
response.Cookies = cookieContainer.GetCookies(response.ResponseUri);
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
return retString;
}
19
View Source File : Utility.Http.cs
License : MIT License
Project Creator : 7Bytes-Studio
License : MIT License
Project Creator : 7Bytes-Studio
public static string Get(string Url, string gettDataStr)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (gettDataStr == "" ? "" : "?") + gettDataStr);
request.Method = "GET";
request.ContentType = "text/html;charset=UTF-8";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
return retString;
}
19
View Source File : HTTP.cs
License : MIT License
Project Creator : 944095635
License : MIT License
Project Creator : 944095635
private byte[] GetByte()
{
byte[] ResponseByte = null;
using (MemoryStream _stream = new MemoryStream())
{
//GZIIP处理
if (response.ContentEncoding != null && response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase))
{
//开始读取流并设置编码方式
new GZipStream(response.GetResponseStream(), CompressionMode.Decompress).CopyTo(_stream, 10240);
}
else
{
//开始读取流并设置编码方式
response.GetResponseStream().CopyTo(_stream, 10240);
}
//获取Byte
ResponseByte = _stream.ToArray();
}
return ResponseByte;
}
19
View Source File : HttpGetSearch.cs
License : MIT License
Project Creator : ABN-SFLookupTechnicalSupport
License : MIT License
Project Creator : ABN-SFLookupTechnicalSupport
private static string ReadResponse(HttpWebRequest webRequest) {
StreamReader Reader;
HttpWebResponse Response;
String ResponseContents = "";
try {
Response = ((HttpWebResponse)(webRequest.GetResponse()));
Reader = new StreamReader(Response.GetResponseStream());
ResponseContents = Reader.ReadToEnd();
Reader.Close();
}
catch (ObjectDisposedException) {
throw;
}
catch (IOException) {
throw;
}
catch (SystemException) {
throw;
}
return ResponseContents;
}
19
View Source File : PrimitiveMethods.Download.cs
License : MIT License
Project Creator : Accelerider
License : MIT License
Project Creator : Accelerider
public static IObservable<(long Offset, int Bytes)> CreateBlockDownloadItem(
Func<Task<(HttpWebResponse response, Stream inputStream)>> streamPairFactory,
BlockTransferContext context) => Observable.Create<(long Offset, int Bytes)>(o =>
{
var cancellationTokenSource = new CancellationTokenSource();
var cancellationToken = cancellationTokenSource.Token;
// Execute copy stream by async.
Task.Run(async () =>
{
try
{
(HttpWebResponse response, Stream outputStream) = await streamPairFactory();
using (response)
using (var inputStream = response.GetResponseStream())
using (outputStream)
{
byte[] buffer = new byte[128 * 1024];
int count;
Guards.ThrowIfNull(inputStream);
// ReSharper disable once PossibleNullReferenceException
while ((count = inputStream.Read(buffer, 0, buffer.Length)) > 0)
{
if (cancellationToken.IsCancellationRequested)
{
Debug.WriteLine($"[CANCELLED] [{DateTime.Now}] BLOCK DOWNLOAD ITEM ({context.Offset})");
o.OnError(new BlockTransferException(context, new OperationCanceledException()));
return;
}
outputStream.Write(buffer, 0, count);
o.OnNext((context.Offset, count));
}
}
o.OnCompleted();
}
catch (Exception e)
{
o.OnError(new BlockTransferException(context, e));
}
}, cancellationToken);
return () =>
{
Debug.WriteLine($"[DISPOSED] [{DateTime.Now}] BLOCK DOWNLOAD ITEM ({context.Offset})");
cancellationTokenSource.Cancel();
};
});
19
View Source File : APIConsumerHelper.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : ActuarialIntelligence
License : BSD 3-Clause "New" or "Revised" License
Project Creator : ActuarialIntelligence
public static ReturnType ReceiveHTTPObjectPointer<ParameterType,ReturnType>
(ParameterType parameterLObject,
string url,
RESTMethodType methodType)
{
HttpWebRequest request = (HttpWebRequest)WebRequest
.Create(url);
request.Method = methodType.ToString();
request.ContentType = "application/json";
JavaScriptSerializer serializer = new JavaScriptSerializer();
using (var sw = new StreamWriter(request.GetRequestStream()))
{
string json = serializer.Serialize(parameterLObject);
sw.Write(json);
sw.Flush();
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream receiveStream = response.GetResponseStream();
string strP = ReadResponseStream(receiveStream);
var result = JsonConvert.DeserializeObject<ReturnType>(strP);
return result;
}
19
View Source File : Requestor.cs
License : MIT License
Project Creator : adoprog
License : MIT License
Project Creator : adoprog
public void PostRequest(string url, string json)
{
try
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
catch (Exception ex)
{
Log.Error("PostToFlow: Action failed to execute", ex);
}
}
19
View Source File : SendToFlow.cs
License : MIT License
Project Creator : adoprog
License : MIT License
Project Creator : adoprog
public void PostRequest(string url, string json)
{
try
{
var httpWebRequest = (HttpWebRequest) WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse) httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
catch
{
// TODO: Use MA logging API to log error
}
}
19
View Source File : BingMapLookup.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private static BingLocationResponse GetResult(HttpWebResponse response)
{
BingLocationResponse result = null;
if (response != null && response.StatusCode == HttpStatusCode.OK)
{
using (var stream = response.GetResponseStream())
{
var serialiser = new DataContractJsonSerializer(typeof(BingLocationResponse));
if (stream != null)
{
result = serialiser.ReadObject(stream) as BingLocationResponse;
}
}
}
return result;
}
19
View Source File : RemotePost.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private static string PostAndGetResponseString(string url, NameValueCollection parameters)
{
if (string.IsNullOrWhiteSpace(url) || (parameters == null || !parameters.HasKeys()))
{
return string.Empty;
}
var httpRequest = (HttpWebRequest)WebRequest.Create(url);
httpRequest.Method = "POST";
httpRequest.ContentType = "application/x-www-form-urlencoded";
var postString = ConstructStringFromParameters(parameters);
var bytedata = Encoding.UTF8.GetBytes(postString);
httpRequest.ContentLength = bytedata.Length;
var requestStream = httpRequest.GetRequestStream();
requestStream.Write(bytedata, 0, bytedata.Length);
requestStream.Close();
var httpWebResponse = (HttpWebResponse)httpRequest.GetResponse();
var responseStream = httpWebResponse.GetResponseStream();
var sb = new StringBuilder();
if (responseStream != null)
{
using (var reader = new StreamReader(responseStream, Encoding.UTF8))
{
string line;
while ((line = reader.ReadLine()) != null)
{
sb.Append(line);
}
}
}
return sb.ToString();
}
19
View Source File : HttpHelper.cs
License : GNU General Public License v3.0
Project Creator : aduskin
License : GNU General Public License v3.0
Project Creator : aduskin
static WebList Http_DownSteam(HttpWebResponse response, Encoding encoding)
{
WebList _web = new WebList
{
Encoding = encoding,
StatusCode = (int)response.StatusCode,
Type = response.ContentType,
AbsoluteUri = response.ResponseUri.AbsoluteUri
};
string header = "";
foreach (string str in response.Headers.AllKeys)
{
if (str == "Set-Cookie")
{
_web.SetCookie = response.Headers[str];
}
else if (str == "Location")
{
_web.Location = response.Headers[str];
}
header = header + str + ":" + response.Headers[str] + "\r\n";
}
string cookie = "";
foreach (Cookie str in response.Cookies)
{
cookie = cookie + str.Name + "=" + str.Value + ";";
}
_web.Header = header;
_web.Cookie = cookie;
#region 下载流
using (Stream stream = response.GetResponseStream())
{
using (MemoryStream file = new MemoryStream())
{
int _value = 0;
byte[] _cache = new byte[1024];
int osize = stream.Read(_cache, 0, 1024);
while (osize > 0)
{
_value += osize;
file.Write(_cache, 0, osize);
osize = stream.Read(_cache, 0, 1024);
}
file.Seek(0, SeekOrigin.Begin);
byte[] _byte = new byte[_value];
file.Read(_byte, 0, _value);
file.Seek(0, SeekOrigin.Begin);
string fileclreplaced = GetFileClreplaced(file);
if (fileclreplaced == "31139")
{
//_web.OriginalSize = _byte.Length;
_web.Byte = Decompress(_byte);
}
else
{
_web.Byte = _byte;
}
}
}
#endregion
return _web;
}
19
View Source File : HttpURLConnectionClient.cs
License : MIT License
Project Creator : Adyen
License : MIT License
Project Creator : Adyen
public string Post(string endpoint, Dictionary<string, string> postParameters, Config config)
{
var dictToString = QueryString(postParameters);
byte[] postBytes = Encoding.UTF8.GetBytes(dictToString);
var httpWebRequest = (HttpWebRequest)WebRequest.Create(endpoint);
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.ContentLength = postBytes.Length;
if (config.Proxy != null)
{
httpWebRequest.Proxy = config.Proxy;
}
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
using (var stream = httpWebRequest.GetRequestStream())
{
stream.Write(postBytes, 0, postBytes.Length);
}
var response = (HttpWebResponse)httpWebRequest.GetResponse();
return new StreamReader(response.GetResponseStream()).ReadToEnd();
}
19
View Source File : HttpURLConnectionClient.cs
License : MIT License
Project Creator : Adyen
License : MIT License
Project Creator : Adyen
public string Request(string endpoint, string json, Config config, bool isApiKeyRequired, RequestOptions requestOptions = null )
{
string responseText = null;
_environment = config.Environment;
var httpWebRequest = GetHttpWebRequest(endpoint, config, isApiKeyRequired, requestOptions );
if (config.HttpRequestTimeout > 0)
{
httpWebRequest.Timeout = config.HttpRequestTimeout;
}
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
try
{
using (var response = (HttpWebResponse) httpWebRequest.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream(), _encoding))
{
responseText = reader.ReadToEnd();
}
}
}
catch (WebException e)
{
HandleWebException(e);
}
return responseText;
}
19
View Source File : HttpURLConnectionClient.cs
License : MIT License
Project Creator : Adyen
License : MIT License
Project Creator : Adyen
public async Task<string> RequestAsync(string endpoint, string json, Config config, bool isApiKeyRequired, RequestOptions requestOptions = null)
{
string responseText = null;
//Set security protocol. Only TLS1.2
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var httpWebRequest = GetHttpWebRequest(endpoint, config, isApiKeyRequired, requestOptions);
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
try
{
using (var response = (HttpWebResponse)await httpWebRequest.GetResponseAsync())
{
using (var reader = new StreamReader(response.GetResponseStream(), _encoding))
{
responseText = await reader.ReadToEndAsync();
}
}
}
catch (WebException e)
{
HandleWebException(e);
}
return responseText;
}
19
View Source File : HttpURLConnectionClient.cs
License : MIT License
Project Creator : Adyen
License : MIT License
Project Creator : Adyen
private static void HandleWebException(WebException e)
{
string responseText = null;
//Add check on actual timeout before returning timeout
if (e.Response == null && e.Status == WebExceptionStatus.Timeout)
{
throw new HttpClientException((int)HttpStatusCode.RequestTimeout, "HTTP Exception timeout", null, "No response", e);
}
//May occur for incorrect certificate: in such case the certificate validation failure is mapped to an UnknownError by Microsoft
if (e.Response == null && e.Status == WebExceptionStatus.UnknownError)
{
throw new HttpClientException((int)HttpStatusCode.Ambiguous, "Potential certificate mismatch", null, e.Message, e);
}
if (e.Response == null)
{
throw new HttpClientException((int)e.Status, "Web Exception", null, "No response", e);
}
var response = (HttpWebResponse)e.Response;
using (var sr = new StreamReader(response.GetResponseStream()))
{
responseText = sr.ReadToEnd();
}
throw new HttpClientException((int)response.StatusCode, "HTTP Exception", response.Headers, responseText, e);
}
19
View Source File : MainForm.cs
License : GNU General Public License v3.0
Project Creator : AgentRev
License : GNU General Public License v3.0
Project Creator : AgentRev
private void UpdateResponse(IAsyncResult result)
{
try
{
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
Stream resStream = response.GetResponseStream();
string tempString;
int count;
StringBuilder sb = new StringBuilder();
byte[] buf = new byte[0x2000];
do
{
count = resStream.Read(buf, 0, buf.Length);
if (count != 0)
{
tempString = Encoding.ASCII.GetString(buf, 0, count);
sb.Append(tempString);
}
}
while (count > 0);
string returnData = sb.ToString();
string dataVer = Regex.Match(returnData, @"FoVChangerVer\[([0-9\.]*?)\]").Groups[1].Value;
string dataSafe = Regex.Match(returnData, @"SafeToUse\[([A-Za-z]*?)\]").Groups[1].Value;
string dataInfo = Regex.Unescape(HttpUtility.HtmlDecode(Regex.Match(returnData, @"UpdateInfo\[(.*?)\]").Groups[1].Value));
string dataDownloadLink = Regex.Match(returnData, @"DownloadLink\[(.*?)\]").Groups[1].Value;
string datareplacedytics = Regex.Match(returnData, @"Googlereplacedytics\[([A-Za-z\-0-9]*?)\]").Groups[1].Value;
string dataIPService = Regex.Match(returnData, @"IPService\[(.*?)\]").Groups[1].Value;
//MessageBox.Show(dataSafe);
if (!String.IsNullOrEmpty(dataSafe) && dataSafe.ToLower() == "vacdetected")
{
this.Invoke(new Action(() =>
{
DialogResult vacResult = MessageBox.Show(this, "It has been reported that this FoV Changer may cause anti-cheat software to trigger a ban. " +
"For any information, please check github.com/AgentRev/CoD-FoV-Changers\n\n" +
"Click 'OK' to exit the program, or 'Cancel' to continue using it AT YOUR OWN RISK.",
"Detection alert", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
if (vacResult == DialogResult.OK)
Application.Exit();
}));
}
//MessageBox.Show(dataVer);
if (!String.IsNullOrEmpty(dataVer) && VersionNum(dataVer) > VersionNum(c_toolVer))
{
this.Invoke(new Action(() =>
{
updateAvailable = true;
if (chkUpdate.Checked && updateNotify)
{
MessageBox.Show(this, "Update v" + dataVer + " is available at MapModNews.com\nClicking the \"Help\" button below will take you to the download page." + (!String.IsNullOrEmpty(dataInfo) ? "\n\nInfos:\n" + dataInfo : ""),
"Update available", MessageBoxButtons.OK, MessageBoxIcon.Information,
MessageBoxDefaultButton.Button1, 0, (!String.IsNullOrEmpty(dataDownloadLink) ? dataDownloadLink : "http://ghostsfov.ftp.sh/"));
lblUpdateAvail.Text = "Update v" + dataVer + " available";
lblUpdateAvail.Enabled = true;
lblUpdateAvail.Visible = true;
TimerBlink.Start();
}
else
{
requestSent = false;
}
}));
}
if (!String.IsNullOrEmpty(datareplacedytics))
{
Greplacedytics.trackingID = datareplacedytics;
}
if (!String.IsNullOrEmpty(dataIPService))
{
Greplacedytics.ipService = dataIPService;
}
}
catch {}
try
{
Greplacedytics.Triggerreplacedytics((string)gameMode.GetValue("c_settingsDirName") + " v" + c_toolVer, firstTime);
}
catch {}
}
19
View Source File : MainForm.cs
License : GNU General Public License v3.0
Project Creator : AgentRev
License : GNU General Public License v3.0
Project Creator : AgentRev
private void UpdateResponse(IAsyncResult result)
{
try
{
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
Stream resStream = response.GetResponseStream();
string tempString;
int count;
StringBuilder sb = new StringBuilder();
byte[] buf = new byte[0x1000];
do
{
count = resStream.Read(buf, 0, buf.Length);
if (count != 0)
{
tempString = Encoding.ASCII.GetString(buf, 0, count);
sb.Append(tempString);
}
}
while (count > 0);
string dataVer = Regex.Match(sb.ToString(), @"FoVChangerVer\[([0-9\.]+)\]").Groups[1].Value;
string dataSafe = Regex.Match(sb.ToString(), @"SafeToUse\[([A-Za-z]+)\]").Groups[1].Value;
//MessageBox.Show(dataVer);
if (!String.IsNullOrEmpty(dataSafe) && dataSafe.ToLower() == "vacdetected")
{
DialogResult vacResult = MessageBox.Show("It has been reported that this FoV Changer may cause Valve Anti-Cheat to trigger a ban. " +
"For any information, please check MapModNews.com.\n\n" +
"Click 'OK' to exit the program, or 'Cancel' to continue using it AT YOUR OWN RISK.",
"Detection alert", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
if (vacResult == DialogResult.OK) Application.Exit();
}
//MessageBox.Show(dataVer);
if (!String.IsNullOrEmpty(dataVer) && VersionNum(dataVer) > VersionNum(c_toolVer))
{
lblUpdateAvail.Text = "└ Update v" + dataVer + " available";
lblUpdateAvail.Enabled = true;
lblUpdateAvail.Visible = true;
if (updateChk) MessageBox.Show("Update v" + dataVer + " for the FoV Changer is available at MapModNews.com",
"Update available", MessageBoxButtons.OK, MessageBoxIcon.Information);
TimerBlink.Start();
}
}
catch { }
requestSent = false;
}
19
View Source File : MainForm.cs
License : GNU General Public License v3.0
Project Creator : AgentRev
License : GNU General Public License v3.0
Project Creator : AgentRev
private void UpdateResponse(IAsyncResult result)
{
try
{
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
Stream resStream = response.GetResponseStream();
string tempString;
int count;
StringBuilder sb = new StringBuilder();
byte[] buf = new byte[0x2000];
do
{
count = resStream.Read(buf, 0, buf.Length);
if (count != 0)
{
tempString = Encoding.ASCII.GetString(buf, 0, count);
sb.Append(tempString);
}
}
while (count > 0);
string dataVer = Regex.Match(sb.ToString(), @"FoVChangerVer\[([0-9\.]*?)\]").Groups[1].Value;
string dataSafe = Regex.Match(sb.ToString(), @"SafeToUse\[([A-Za-z]*?)\]").Groups[1].Value;
string dataInfo = Regex.Unescape(HttpUtility.HtmlDecode(Regex.Match(sb.ToString(), @"UpdateInfo\[(.*?)\]").Groups[1].Value));
//MessageBox.Show(dataVer);
if (!String.IsNullOrEmpty(dataSafe) && dataSafe.ToLower() == "vacdetected")
{
this.Invoke(new Action(() =>
{
DialogResult vacResult = MessageBox.Show(this, "It has been reported that this FoV Changer may cause Valve Anti-Cheat to trigger a ban. " +
"For any information, please check MapModNews.com.\n\n" +
"Click 'OK' to exit the program, or 'Cancel' to continue using it AT YOUR OWN RISK.",
"Detection alert", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
if (vacResult == DialogResult.OK)
Application.Exit();
}));
}
//MessageBox.Show(dataVer);
if (!String.IsNullOrEmpty(dataVer) && VersionNum(dataVer) > VersionNum(c_toolVer))
{
this.Invoke(new Action(() =>
{
if (updateChk)
MessageBox.Show(this, "Update v" + dataVer + " for the FoV Changer is available at MapModNews.com, or can be downloaded directly \nby clicking the \"Help\" button below." + (!String.IsNullOrEmpty(dataInfo) ? "\n\nAdditional infos:\n" + dataInfo : ""),
"Update available", MessageBoxButtons.OK, MessageBoxIcon.Information,
MessageBoxDefaultButton.Button1, 0, "http://mw3fov.ftp.sh/");
lblUpdateAvail.Text = " - Update v" + dataVer + " available";
lblUpdateAvail.Enabled = true;
lblUpdateAvail.Visible = true;
TimerBlink.Start();
}));
}
}
catch {}
requestSent = false;
}
19
View Source File : mainForm.cs
License : MIT License
Project Creator : ajohns6
License : MIT License
Project Creator : ajohns6
private void pullJSON(object sender, EventArgs e)
{
string url = "https://api.jsonbin.io/b/5f05f3e0a62f9b4b27613c5a/latest";
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
File.WriteAllText(onlineJSON, reader.ReadToEnd());
}
populateGrid(onlineJSON);
MessageBox.Show("Your PAK list has been successfully updated.", "Done", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
19
View Source File : mainForm.cs
License : MIT License
Project Creator : ajohns6
License : MIT License
Project Creator : ajohns6
private void pullJSON()
{
string url = "https://api.jsonbin.io/b/5f05f3e0a62f9b4b27613c5a/latest";
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
File.WriteAllText(onlineJSON, reader.ReadToEnd());
}
MessageBox.Show("Your PAK List has been successfully updated.", "Done", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
19
View Source File : updateForm.cs
License : MIT License
Project Creator : ajohns6
License : MIT License
Project Creator : ajohns6
private void checkUpdate(object sender, EventArgs e)
{
if (!progressForm.IsConnectedToInternet())
{
this.Dispose();
return;
}
string url = "https://api.github.com/repos/ajohns6/SM64-NX-Launcher/releases";
string releaseString = "";
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Accept = "application/json";
request.Method = "GET";
request.UserAgent = "Foo";
try
{
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
releaseString = reader.ReadToEnd();
}
}
catch
{
this.Dispose();
return;
}
Application.DoEvents();
var releaseList = JsonConvert.DeserializeObject<List<release>>(releaseString);
if (releaseList[0].tag_name != ("v" + version))
{
this.statusLabel.Text = "Downloading " + releaseList[0].tag_name + "...";
this.progBar.Visible = true;
string tempPath = Path.Combine(Path.GetTempPath(),
"sm64nxlauncherinstaller",
version);
string zipPath = Path.Combine(tempPath, "installer.zip");
mainForm.DeleteDirectory(tempPath);
Task.Run(() =>
{
using (var client = new WebClient())
{
if (!Directory.Exists(tempPath))
{
Directory.CreateDirectory(tempPath);
}
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(downloadProgress);
client.DownloadFileCompleted += new AsyncCompletedEventHandler(downloadComplete);
Uri installerLink = new Uri(releaseList[0].replacedets[0].browser_download_url);
client.DownloadFileAsync(installerLink, zipPath);
}
});
progBar.Maximum = 100;
Application.DoEvents();
do
{
progBar.Value = progress;
} while (progress < 100);
do
{
Application.DoEvents();
} while (!complete);
this.statusLabel.Text = "Extracting installer...";
Task.Run(() =>
{
bool unzipped = false;
do
{
try
{
ZipFile.ExtractToDirectory(zipPath, tempPath);
unzipped = true;
}
catch { }
} while (!unzipped);
}).Wait();
ProcessStartInfo installStart = new ProcessStartInfo();
installStart.FileName = Path.Combine(tempPath, "setup.exe");
Process installer = new Process();
installer.StartInfo = installStart;
installer.Start();
Application.Exit();
}
this.Close();
}
19
View Source File : Response.cs
License : MIT License
Project Creator : alen-smajic
License : MIT License
Project Creator : alen-smajic
public static Response FromWebResponse(IAsyncRequest request, HttpWebResponse apiResponse, Exception apiEx) {
Response response = new Response();
response.Request = request;
if (null != apiEx) {
response.AddException(apiEx);
}
// timeout: API response is null
if (null == apiResponse) {
response.AddException(new Exception("No Reponse."));
} else {
// https://www.mapbox.com/api-doreplacedentation/#rate-limit-headers
if (null != apiResponse.Headers) {
response.Headers = new Dictionary<string, string>();
for (int i = 0; i < apiResponse.Headers.Count; i++) {
// TODO: implement .Net Core / UWP implementation
string key = apiResponse.Headers.Keys[i];
string val = apiResponse.Headers[i];
response.Headers.Add(key, val);
if (key.Equals("X-Rate-Limit-Interval", StringComparison.InvariantCultureIgnoreCase)) {
int limitInterval;
if (int.TryParse(val, out limitInterval)) { response.XRateLimitInterval = limitInterval; }
} else if (key.Equals("X-Rate-Limit-Limit", StringComparison.InvariantCultureIgnoreCase)) {
long limitLimit;
if (long.TryParse(val, out limitLimit)) { response.XRateLimitLimit = limitLimit; }
} else if (key.Equals("X-Rate-Limit-Reset", StringComparison.InvariantCultureIgnoreCase)) {
double unixTimestamp;
if (double.TryParse(val, out unixTimestamp)) {
response.XRateLimitReset = UnixTimestampUtils.From(unixTimestamp);
}
} else if (key.Equals("Content-Type", StringComparison.InvariantCultureIgnoreCase)) {
response.ContentType = val;
}
}
}
if (apiResponse.StatusCode != HttpStatusCode.OK) {
response.AddException(new Exception(string.Format("{0}: {1}", apiResponse.StatusCode, apiResponse.StatusDescription)));
}
int statusCode = (int)apiResponse.StatusCode;
response.StatusCode = statusCode;
if (429 == statusCode) {
response.AddException(new Exception("Rate limit hit"));
}
if (null != apiResponse) {
using (Stream responseStream = apiResponse.GetResponseStream()) {
byte[] buffer = new byte[0x1000];
int bytesRead;
using (MemoryStream ms = new MemoryStream()) {
while (0 != (bytesRead = responseStream.Read(buffer, 0, buffer.Length))) {
ms.Write(buffer, 0, bytesRead);
}
response.Data = ms.ToArray();
}
}
apiResponse.Close();
}
}
return response;
}
19
View Source File : MKMInteract.cs
License : GNU Affero General Public License v3.0
Project Creator : alexander-pick
License : GNU Affero General Public License v3.0
Project Creator : alexander-pick
public static XmlDoreplacedent MakeRequest(string url, string method, string body = null)
{
// throw the exception ourselves to prevent sending requests to MKM that would end with this error
// because MKM tends to revoke the user's app token if it gets too many requests above the limit
// the 429 code is the same MKM uses for this error
if (denyAdditionalRequests)
{
// MKM resets the counter at 0:00 CET. CET is two hours ahead of UCT, so if it is after 22:00 of the same day
// the denial was triggered, that means the 0:00 CET has preplaceded and we can reset the deny
if (DateTime.UtcNow.Date == denyTime.Date && DateTime.UtcNow.Hour < 22)
throw new HttpListenerException(429, "Too many requests. Wait for 0:00 CET for request counter to reset.");
else
denyAdditionalRequests = false;
}
// enforce the maxRequestsPerMinute limit - technically it's just an approximation as the requests
// can arrive to MKM with some delay, but it should be close enough
var now = DateTime.Now;
while (requestTimes.Count > 0 && (now - requestTimes.Peek()).TotalSeconds > 60)
{
requestTimes.Dequeue();// keep only times of requests in the past 60 seconds
}
if (requestTimes.Count >= maxRequestsPerMinute)
{
// wait until 60.01 seconds preplaceded since the oldest request
// we know (now - peek) is <= 60, otherwise it would get dequeued above,
// so we are preplaceding a positive number to sleep
System.Threading.Thread.Sleep(
60010 - (int)(now - requestTimes.Peek()).TotalMilliseconds);
requestTimes.Dequeue();
}
requestTimes.Enqueue(DateTime.Now);
XmlDoreplacedent doc = new XmlDoreplacedent();
for (int numAttempts = 0; numAttempts < MainView.Instance.Config.MaxTimeoutRepeat; numAttempts++)
{
try
{
var request = WebRequest.CreateHttp(url);
request.Method = method;
request.Headers.Add(HttpRequestHeader.Authorization, header.GetAuthorizationHeader(method, url));
request.Method = method;
if (body != null)
{
request.ServicePoint.Expect100Continue = false;
request.ContentLength = System.Text.Encoding.UTF8.GetByteCount(body);
request.ContentType = "text/xml";
var writer = new StreamWriter(request.GetRequestStream());
writer.Write(body);
writer.Close();
}
var response = request.GetResponse() as HttpWebResponse;
// just for checking EoF, it is not accessible directly from the Stream object
// Empty streams can be returned for example for article fetches that result in 0 matches (happens regularly when e.g. seeking nonfoils in foil-only promo sets).
// Preplaceding empty stream to doc.Load causes exception and also sometimes seems to screw up the XML parser
// even when the exception is handled and it then causes problems for subsequent calls => first check if the stream is empty
StreamReader s = new StreamReader(response.GetResponseStream());
if (!s.EndOfStream)
doc.Load(s);
s.Close();
int requestCount = int.Parse(response.Headers.Get("X-Request-Limit-Count"));
int requestLimit = int.Parse(response.Headers.Get("X-Request-Limit-Max"));
if (requestCount >= requestLimit)
{
denyAdditionalRequests = true;
denyTime = DateTime.UtcNow;
}
MainView.Instance.Invoke(new MainView.UpdateRequestCountCallback(MainView.Instance.UpdateRequestCount), requestCount, requestLimit);
break;
}
catch (WebException webEx)
{
// timeout can be either on our side (Timeout) or on server
bool isTimeout = webEx.Status == WebExceptionStatus.Timeout;
if (webEx.Status == WebExceptionStatus.ProtocolError)
{
if (webEx.Response is HttpWebResponse response)
{
isTimeout = response.StatusCode == HttpStatusCode.GatewayTimeout
|| response.StatusCode == HttpStatusCode.ServiceUnavailable;
}
}
// handle only timeouts, client handles other exceptions
if (isTimeout && numAttempts + 1 < MainView.Instance.Config.MaxTimeoutRepeat)
System.Threading.Thread.Sleep(1500); // wait and try again
else
throw webEx;
}
}
return doc;
}
19
View Source File : BybitRestRequestBuilder.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public static JToken CreatePrivateGetQuery(Client client, string end_point, Dictionary<string, string> parameters)
{
//int time_factor = 1;
//if (client.NetMode == "Main")
// time_factor = 0;
Dictionary<string, string> sorted_params = parameters.OrderBy(pair => pair.Key).ToDictionary(pair => pair.Key, pair => pair.Value);
StringBuilder sb = new StringBuilder();
foreach (var param in sorted_params)
{
sb.Append(param.Key + $"=" + param.Value + $"&");
}
long nonce = Utils.GetMillisecondsFromEpochStart();
string str_params = sb.ToString() + "timestamp=" + (nonce).ToString();
string url = client.RestUrl + end_point + $"?" + str_params;
Uri uri = new Uri(url + $"&sign=" + BybitSigner.CreateSignature(client, str_params));
var http_web_request = (HttpWebRequest)WebRequest.Create(uri);
http_web_request.Method = "Get";
http_web_request.Host = client.RestUrl.Replace($"https://", "");
HttpWebResponse http_web_response = (HttpWebResponse)http_web_request.GetResponse();
string response_msg;
using (var stream = http_web_response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream ?? throw new InvalidOperationException()))
{
response_msg = reader.ReadToEnd();
}
}
http_web_response.Close();
if (http_web_response.StatusCode != HttpStatusCode.OK)
{
throw new Exception("Failed request " + response_msg);
}
return JToken.Parse(response_msg);
}
19
View Source File : BybitRestRequestBuilder.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public static JToken CreatePrivatePostQuery(Client client, string end_point, Dictionary<string, string> parameters)
{
parameters.Add("timestamp", (Utils.GetMillisecondsFromEpochStart()).ToString());
Dictionary<string, string> sorted_params = parameters.OrderBy(pair => pair.Key).ToDictionary(pair => pair.Key, pair => pair.Value);
StringBuilder sb = new StringBuilder();
foreach (var param in sorted_params)
{
if (param.Value == "false" || param.Value == "true")
sb.Append("\"" + param.Key + "\":" + param.Value + ",");
else
sb.Append("\"" + param.Key + "\":\"" + param.Value + "\",");
}
StringBuilder sb_signer = new StringBuilder();
foreach (var param in sorted_params)
{
sb_signer.Append(param.Key + $"=" + param.Value + $"&");
}
string str_signer = sb_signer.ToString();
str_signer = str_signer.Remove(str_signer.Length - 1);
sb.Append("\"sign\":\"" + BybitSigner.CreateSignature(client, str_signer) + "\""); // api_key=bLP2z8x0sEeFHgt14S&close_on_trigger=False&order_link_id=&order_type=Limit&price=11018.00&qty=1&side=Buy&symbol=BTCUSD&time_in_force=GoodTillCancel×tamp=1600513511844
// api_key=bLP2z8x0sEeFHgt14S&close_on_trigger=False&order_link_id=&order_type=Limit&price=10999.50&qty=1&side=Buy&symbol=BTCUSD&time_in_force=GoodTillCancel×tamp=1600514673126
// {"api_key":"bLP2z8x0sEeFHgt14S","close_on_trigger":"False","order_link_id":"","order_type":"Limit","price":"11050.50","qty":"1","side":"Buy","symbol":"BTCUSD","time_in_force":"GoodTillCancel","timestamp":"1600515164173","sign":"fb3c69fa5d30526810a4b60fe4b8f216a3baf2c81745289ff7ddc21ab8232ccc"}
string url = client.RestUrl + end_point;
string str_data = "{" + sb.ToString() + "}";
byte[] data = Encoding.UTF8.GetBytes(str_data);
Uri uri = new Uri(url);
var http_web_request = (HttpWebRequest)WebRequest.Create(uri);
http_web_request.Method = "POST";
http_web_request.ContentType = "application/json";
http_web_request.ContentLength = data.Length;
using (Stream req_tream = http_web_request.GetRequestStream())
{
req_tream.Write(data, 0, data.Length);
}
HttpWebResponse httpWebResponse = (HttpWebResponse)http_web_request.GetResponse();
string response_msg;
using (var stream = httpWebResponse.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream))
{
response_msg = reader.ReadToEnd();
}
}
httpWebResponse.Close();
return JToken.Parse(response_msg);
}
19
View Source File : BitMaxProClient.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
private string GetData(string apiPath, bool auth = false, string accGroup = null, string jsonContent = null,
string orderId = null, string time = null, Method method = Method.GET, bool need = false)
{
lock (_queryLocker)
{
try
{
Uri uri;
HttpWebRequest httpWebRequest;
if (!auth)
{
uri = new Uri(_baseUrl + "api/pro/v1/" + apiPath);
httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
}
else
{
if (accGroup == null)
{
uri = new Uri(_baseUrl + "api/pro/v1/" + apiPath);
}
else
{
var str = _baseUrl + accGroup + "/" + "api/pro/v1/" + apiPath;
if (need)
{
str += "?n=10&executedOnly=True";
}
uri = new Uri(str);
}
string timestamp;
if (time == null)
{
timestamp = TimeManager.GetUnixTimeStampMilliseconds().ToString();
}
else
{
timestamp = time;
}
string signatureMsg;
if (orderId == null)
{
signatureMsg = timestamp + "+" + apiPath;
}
else
{
//signatureMsg = timestamp + "+" + apiPath + "+" + orderId;
signatureMsg = timestamp + "+" + "order";
}
if (signatureMsg.EndsWith("cash/balance"))
{
signatureMsg = signatureMsg.Replace("cash/", "");
//signatureMsg = signatureMsg.Remove(signatureMsg.Length - 11, 4);
}
if (signatureMsg.EndsWith("margin/balance"))
{
signatureMsg = signatureMsg.Replace("margin/", "");
//signatureMsg = signatureMsg.Remove(signatureMsg.Length - 13, 6);
}
var codedSignature = CreateSignature(signatureMsg);
httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
httpWebRequest.Headers.Add("x-auth-key", _apiKey);
httpWebRequest.Headers.Add("x-auth-signature", codedSignature);
httpWebRequest.Headers.Add("x-auth-timestamp", timestamp.ToString());
if (orderId != null)
{
httpWebRequest.Headers.Add("x-auth-coid", orderId);
}
}
httpWebRequest.Method = method.ToString();
if (jsonContent != null)
{
var data = Encoding.UTF8.GetBytes(jsonContent);
httpWebRequest.ContentType = "application/json";
httpWebRequest.ContentLength = data.Length;
using (Stream requestStream = httpWebRequest.GetRequestStream())
{
requestStream.Write(data, 0, data.Length);
}
}
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
string responseMsg;
using (var stream = httpWebResponse.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream ?? throw new InvalidOperationException()))
{
responseMsg = reader.ReadToEnd();
}
}
httpWebResponse.Close();
return responseMsg;
}
catch (InvalidOperationException invalidOperationException)
{
SendLogMessage("Failed to get stream to read response from server.. " + invalidOperationException.Message, LogMessageType.Error);
return null;
}
catch (Exception exception)
{
SendLogMessage(exception.Message, LogMessageType.Error);
return null;
}
}
}
19
View Source File : BybitRestRequestBuilder.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public static JToken CreatePublicGetQuery(Client client, string end_point)
{
string url = client.RestUrl + end_point;
Uri uri = new Uri(url);
var http_web_request = (HttpWebRequest)WebRequest.Create(uri);
HttpWebResponse http_web_response = (HttpWebResponse)http_web_request.GetResponse();
string response_msg;
using (var stream = http_web_response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream ?? throw new InvalidOperationException()))
{
response_msg = reader.ReadToEnd();
}
}
http_web_response.Close();
if (http_web_response.StatusCode != HttpStatusCode.OK)
{
throw new Exception("Failed request " + response_msg);
}
return JToken.Parse(response_msg);
}
19
View Source File : ServerSms.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
private string[] _smsc_send_cmd(string cmd, string arg, string[] files = null)
{
arg = "login=" + _urlencode(SmscLogin) + "&psw=" + _urlencode(SmscPreplacedword) + "&fmt=1&charset=" + SmscCharset + "&" + arg;
string url = (SmscHttps ? "https" : "http") + "://smsc.ru/sys/" + cmd + ".php" + (SmscPost ? "" : "?" + arg);
string ret;
int i = 0;
HttpWebRequest request;
StreamReader sr;
HttpWebResponse response;
do
{
if (i > 0)
System.Threading.Thread.Sleep(2000 + 1000 * i);
if (i == 2)
url = url.Replace("://smsc.ru/", "://www2.smsc.ru/");
request = (HttpWebRequest)WebRequest.Create(url);
if (SmscPost) {
request.Method = "POST";
string postHeader, boundary = "----------" + DateTime.Now.Ticks.ToString("x");
byte[] postHeaderBytes, boundaryBytes = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n"), tbuf;
StringBuilder sb = new StringBuilder();
int bytesRead;
byte[] output = new byte[0];
if (files == null) {
request.ContentType = "application/x-www-form-urlencoded";
output = Encoding.UTF8.GetBytes(arg);
request.ContentLength = output.Length;
}
else {
request.ContentType = "multipart/form-data; boundary=" + boundary;
string[] par = arg.Split('&');
int fl = files.Length;
for (int pcnt = 0; pcnt < par.Length + fl; pcnt++)
{
sb.Clear();
sb.Append("--");
sb.Append(boundary);
sb.Append("\r\n");
sb.Append("Content-Disposition: form-data; name=\"");
bool pof = pcnt < fl;
String[] nv = new String[0];
if (pof)
{
sb.Append("File" + (pcnt + 1));
sb.Append("\"; filename=\"");
sb.Append(Path.GetFileName(files[pcnt]));
}
else {
nv = par[pcnt - fl].Split('=');
sb.Append(nv[0]);
}
sb.Append("\"");
sb.Append("\r\n");
sb.Append("Content-Type: ");
sb.Append(pof ? "application/octet-stream" : "text/plain; charset=\"" + SmscCharset + "\"");
sb.Append("\r\n");
sb.Append("Content-Transfer-Encoding: binary");
sb.Append("\r\n");
sb.Append("\r\n");
postHeader = sb.ToString();
postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);
output = _concatb(output, postHeaderBytes);
if (pof)
{
FileStream fileStream = new FileStream(files[pcnt], FileMode.Open, FileAccess.Read);
// Write out the file contents
byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)fileStream.Length))];
bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
tbuf = buffer;
Array.Resize(ref tbuf, bytesRead);
output = _concatb(output, tbuf);
}
}
else {
byte[] vl = Encoding.UTF8.GetBytes(nv[1]);
output = _concatb(output, vl);
}
output = _concatb(output, Encoding.UTF8.GetBytes("\r\n"));
}
output = _concatb(output, boundaryBytes);
request.ContentLength = output.Length;
}
Stream requestStream = request.GetRequestStream();
requestStream.Write(output, 0, output.Length);
}
try
{
response = (HttpWebResponse)request.GetResponse();
sr = new StreamReader(response.GetResponseStream());
ret = sr.ReadToEnd();
}
catch (WebException) {
ret = "";
}
}
while (ret == "" && ++i < 4);
if (ret == "") {
if (SmscDebug)
_print_debug("Ошибка чтения адреса: " + url);
ret = ","; // bogus response / фиктивный ответ
}
char delim = ',';
if (cmd == "status")
{
string[] par = arg.Split('&');
for (i = 0; i < par.Length; i++)
{
string[] lr = par[i].Split("=".ToCharArray(), 2);
if (lr[0] == "id" && lr[1].IndexOf("%2c") > 0) // comma in id - multiple request / запятая в id - множественный запрос
delim = '\n';
}
}
return ret.Split(delim);
}
19
View Source File : BitMexClient.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public string CreateQuery(string method, string function, Dictionary<string, string> param = null, bool auth = false)
{
lock (_queryHttpLocker)
{
//Wait for RateGate
_rateGate.WaitToProceed();
string paramData = BuildQueryData(param);
string url = "/api/v1" + function + ((method == "GET" && paramData != "") ? "?" + paramData : "");
string postData = (method != "GET") ? paramData : "";
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(_domain + url);
webRequest.Method = method;
if (auth)
{
string nonce = GetNonce().ToString();
string message = method + url + nonce + postData;
byte[] signatureBytes = Hmacsha256(Encoding.UTF8.GetBytes(_secKey), Encoding.UTF8.GetBytes(message));
string signatureString = ByteArrayToString(signatureBytes);
webRequest.Headers.Add("api-nonce", nonce);
webRequest.Headers.Add("api-key", _id);
webRequest.Headers.Add("api-signature", signatureString);
}
try
{
if (postData != "")
{
webRequest.ContentType = "application/x-www-form-urlencoded";
var data = Encoding.UTF8.GetBytes(postData);
using (var stream = webRequest.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
}
using (WebResponse webResponse = webRequest.GetResponse())
using (Stream str = webResponse.GetResponseStream())
using (StreamReader sr = new StreamReader(str))
{
return sr.ReadToEnd();
}
}
catch (WebException wex)
{
using (HttpWebResponse response = (HttpWebResponse)wex.Response)
{
if (response == null)
throw;
using (Stream str = response.GetResponseStream())
{
using (StreamReader sr = new StreamReader(str))
{
string error = sr.ReadToEnd();
if (ErrorEvent != null)
{
ErrorEvent(error);
}
return sr.ReadToEnd();
}
}
}
}
}
}
19
View Source File : RestRequestBuilder.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public string SendPostQuery(string method, string url, string endPoint, byte[] data, Dictionary<string, string> headers)
{
Uri uri = new Uri(url + endPoint);
var httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
httpWebRequest.Method = method;
httpWebRequest.Accept = "application/json";
httpWebRequest.ContentType = "application/json";
foreach (var header in headers)
{
httpWebRequest.Headers.Add(header.Key, header.Value);
}
httpWebRequest.ContentLength = data.Length;
using (Stream reqStream = httpWebRequest.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
reqStream.Close();
}
string responseMsg;
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var stream = httpWebResponse.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream ?? throw new InvalidOperationException()))
{
responseMsg = reader.ReadToEnd();
}
}
return responseMsg;
}
19
View Source File : RestRequestBuilder.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public string SendGetQuery(string method, string baseUri, string endPoint, Dictionary<string, string> headers)
{
Uri uri = new Uri(baseUri + endPoint);
if (uri.ToString().Contains("?"))
{
var t = 6;
}
var httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
httpWebRequest.Method = method;
httpWebRequest.Accept = "application/json";
httpWebRequest.ContentType = "application/json";
foreach (var header in headers)
{
httpWebRequest.Headers.Add(header.Key, header.Value);
}
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
string responseMsg;
using (var stream = httpWebResponse.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream ?? throw new InvalidOperationException()))
{
responseMsg = reader.ReadToEnd();
}
}
httpWebResponse.Close();
if (httpWebResponse.StatusCode != HttpStatusCode.OK)
{
throw new Exception("Failed request " + responseMsg);
}
return responseMsg;
}
19
View Source File : HitbtcClient.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public string CreateQuery(string method, string endpoint, string pubKey = "", string secKey = "", bool isAuth = false)
{
lock (_queryHttpLocker)
{
try
{
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(_baseUrl + endpoint);
request.Method = method.ToUpper();
request.Accept = "application/json; charset=utf-8";
if (isAuth)
{
//For Basic Authentication
string authInfo = pubKey + ":" + secKey;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
request.Headers["Authorization"] = "Basic " + authInfo;
var response = (HttpWebResponse) request.GetResponse();
string strResponse = "";
using (var sr = new StreamReader(response.GetResponseStream()))
{
strResponse = sr.ReadToEnd();
}
return strResponse;
}
else
{
var response = (HttpWebResponse) request.GetResponse();
string strResponse = "";
using (var sr = new StreamReader(response.GetResponseStream()))
{
strResponse = sr.ReadToEnd();
}
return strResponse;
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return null;
}
}
}
19
View Source File : KrakenRestApi.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
private JsonObject QueryPublic(string a_sMethod, string props = null)
{
string address = string.Format("{0}/{1}/public/{2}", _url, _version, a_sMethod);
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(address);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
lock (_queryLocker)
{
try
{
if (props != null)
{
using (var writer = new StreamWriter(webRequest.GetRequestStream()))
{
writer.Write(props);
}
}
}
catch (Exception)
{
//Thread.Sleep(2000);
if (props != null)
{
using (var writer = new StreamWriter(webRequest.GetRequestStream()))
{
writer.Write(props);
}
}
}
//Wait for RateGate
_rateGate.WaitToProceed();
}
//Make the request
try
{
//ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
using (WebResponse webResponse = webRequest.GetResponse())
{
using (Stream str = webResponse.GetResponseStream())
{
using (StreamReader sr = new StreamReader(str))
{
return (JsonObject)JsonConvert.Import(sr);
}
}
}
}
catch (WebException wex)
{
using (HttpWebResponse response = (HttpWebResponse)wex.Response)
{
using (Stream str = response.GetResponseStream())
{
using (StreamReader sr = new StreamReader(str))
{
if (response.StatusCode != HttpStatusCode.InternalServerError)
{
throw;
}
return (JsonObject)JsonConvert.Import(sr);
}
}
}
}
}
19
View Source File : KrakenRestApi.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
private JsonObject QueryPrivate(string a_sMethod, string props = null)
{
// generate a 64 bit nonce using a timestamp at tick resolution
Int64 nonce = DateTime.Now.Ticks;
props = "nonce=" + nonce + props;
string path = string.Format("/{0}/private/{1}", _version, a_sMethod);
string address = _url + path;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(address);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
webRequest.Headers.Add("API-Key", _key);
byte[] base64DecodedSecred = Convert.FromBase64String(_secret);
var np = nonce + Convert.ToChar(0) + props;
var pathBytes = Encoding.UTF8.GetBytes(path);
var hash256Bytes = sha256_hash(np);
var z = new byte[pathBytes.Count() + hash256Bytes.Count()];
pathBytes.CopyTo(z, 0);
hash256Bytes.CopyTo(z, pathBytes.Count());
var signature = getHash(base64DecodedSecred, z);
webRequest.Headers.Add("API-Sign", Convert.ToBase64String(signature));
if (props != null)
{
using (var writer = new StreamWriter(webRequest.GetRequestStream()))
{
writer.Write(props);
}
}
//Make the request
try
{
//Wait for RateGate
_rateGate.WaitToProceed();
//Thread.Sleep(2000);
using (WebResponse webResponse = webRequest.GetResponse())
{
using (Stream str = webResponse.GetResponseStream())
{
using (StreamReader sr = new StreamReader(str))
{
return (JsonObject)JsonConvert.Import(sr);
}
}
}
}
catch (WebException wex)
{
using (HttpWebResponse response = (HttpWebResponse)wex.Response)
{
using (Stream str = response.GetResponseStream())
{
using (StreamReader sr = new StreamReader(str))
{
if (response.StatusCode != HttpStatusCode.InternalServerError)
{
throw;
}
return (JsonObject)JsonConvert.Import(sr);
}
}
}
}
}
19
View Source File : RestChannel.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public string SendGetQuery(string baseUri, string endPoint)
{
Uri uri = new Uri(baseUri + endPoint);
var httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
string responseMsg;
using (var stream = httpWebResponse.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream ?? throw new InvalidOperationException()))
{
responseMsg = reader.ReadToEnd();
}
}
httpWebResponse.Close();
if (httpWebResponse.StatusCode != HttpStatusCode.OK)
{
throw new Exception("Failed request " + responseMsg);
}
return responseMsg;
}
19
View Source File : RestChannel.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public string SendPostQuery(string url, string endPoint, byte[] data, Dictionary<string, string> headers)
{
Uri uri = new Uri(url + endPoint);
var httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
httpWebRequest.Method = "post";
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
foreach (var header in headers)
{
httpWebRequest.Headers.Add(header.Key, header.Value);
}
httpWebRequest.ContentLength = data.Length;
using (Stream reqStream = httpWebRequest.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
reqStream.Close();
}
string responseMsg;
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var stream = httpWebResponse.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream ?? throw new InvalidOperationException()))
{
responseMsg = reader.ReadToEnd();
}
}
return responseMsg;
}
19
View Source File : ZBServer.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
private string RequestCandlesFromExchange(string needIntervalForQuery, string security)
{
Uri uri = new Uri(UriForCandles + $"market={security}&type={needIntervalForQuery}");
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
var httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
if (httpWebResponse.StatusCode != HttpStatusCode.OK)
{
throw new Exception("Failed to get candles on the instrument " + security);
}
string responseMsg;
using (var stream = httpWebResponse.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream ?? throw new InvalidOperationException()))
{
responseMsg = reader.ReadToEnd();
}
}
httpWebResponse.Close();
return responseMsg;
}
19
View Source File : main.cs
License : GNU General Public License v3.0
Project Creator : ALIILAPRO
License : GNU General Public License v3.0
Project Creator : ALIILAPRO
private void btngetproxy_Click(object sender, EventArgs e)
{
this.ProxyList.Clear();
this.lblproxy.Text = "0";
try
{
HttpWebResponse response = (HttpWebResponse)((HttpWebRequest)WebRequest.Create("https://api.proxyscrape.com?request=getproxies&proxytype=http&timeout=10000&country=all&ssl=all&anonymity=all")).GetResponse();
string end = new StreamReader(response.GetResponseStream()).ReadToEnd();
MatchCollection matchCollections = new Regex("[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}:[0-9]{1,5}").Matches(end);
try
{
try
{
foreach (object obj in matchCollections)
{
Match objectValue = (Match)RuntimeHelpers.GetObjectValue(obj);
this.ProxyList.Add(objectValue.Value);
}
}
finally
{
}
}
finally
{
}
int List = this.ProxyList.Count;
this.lblproxy.Text = string.Concat(new string[]
{
List.ToString()
});
List = this.ProxyList.Count;
this.lblproxy.Text = List.ToString();
}
catch (Exception error)
{
MessageBox.Show(error.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
19
View Source File : main.cs
License : GNU General Public License v3.0
Project Creator : ALIILAPRO
License : GNU General Public License v3.0
Project Creator : ALIILAPRO
private void mtd(object Proxiess)
{
bool start = this._start;
if (start)
{
try
{
string host = Proxiess.ToString().Split(new char[]
{
':'
})[0];
string value = Proxiess.ToString().Split(new char[]
{
':'
})[1];
WebProxy proxy = new WebProxy(host, Convert.ToInt32(value));
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.cloudflareclient.com/v0a745/reg");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add("Accept-Encoding", "gzip");
httpWebRequest.ContentType = "application/json; charset=UTF-8";
httpWebRequest.Host = "api.cloudflareclient.com";
httpWebRequest.KeepAlive = true;
httpWebRequest.UserAgent = "okhttp/3.12.1";
httpWebRequest.Proxy = proxy;
string install_id = this.GenerateUniqCode(22);
string key = this.GenerateUniqCode(43) + "=";
string tos = DateTime.UtcNow.ToString("yyyy-MM-ddTHH\\:mm\\:ss.fff") + "+07:00";
string fcm_token = install_id + ":APA91b" + this.GenerateUniqCode(134);
string referer = this.txtid.Text;
string type = "Android";
string locale = "en-GB";
var body = new
{
install_id = install_id,
key = key,
tos = tos,
fcm_token = fcm_token,
referrer = referer,
warp_enabled = false,
type = type,
locale = locale
};
string jsonBody = JsonConvert.SerializeObject(body);
using (StreamWriter sw = new StreamWriter(httpWebRequest.GetRequestStream()))
{
sw.Write(jsonBody);
}
HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (StreamReader sw = new StreamReader(httpResponse.GetResponseStream()))
{
string result = sw.ReadToEnd();
}
httpResponse = null;
this._test++;
this._send++;
this.lblgood.Text = this._send.ToString();
this.lbltest.Text = this._test.ToString();
this.lblgb.Text = lblgood.Text + " GB Successfully added to your account.";
}
catch
{
this._test++;
this._error++;
this.lblbad.Text = this._error.ToString();
this.lbltest.Text = this._test.ToString();
}
}
}
19
View Source File : WebUtils.cs
License : Apache License 2.0
Project Creator : alipay
License : Apache License 2.0
Project Creator : alipay
public string GetResponsereplacedtring(HttpWebResponse rsp, Encoding encoding)
{
StringBuilder result = new StringBuilder();
Stream stream = null;
StreamReader reader = null;
try
{
// 以字符流的方式读取HTTP响应
stream = rsp.GetResponseStream();
reader = new StreamReader(stream, encoding);
// 按字符读取并写入字符串缓冲
int ch = -1;
while ((ch = reader.Read()) > -1)
{
// 过滤结束符
char c = (char)ch;
if (c != '\0')
{
result.Append(c);
}
}
}
finally
{
// 释放资源
if (reader != null) reader.Close();
if (stream != null) stream.Close();
if (rsp != null) rsp.Close();
}
return result.ToString();
}
19
View Source File : AlipayMobilePublicMultiMediaClient.cs
License : Apache License 2.0
Project Creator : alipay
License : Apache License 2.0
Project Creator : alipay
public void GetResponsereplacedtream(Stream outStream, HttpWebResponse rsp)
{
StringBuilder result = new StringBuilder();
Stream stream = null;
StreamReader reader = null;
BinaryWriter writer = null;
try
{
// 以字符流的方式读取HTTP响应
stream = rsp.GetResponseStream();
reader = new StreamReader(stream);
writer = new BinaryWriter(outStream);
//stream.CopyTo(outStream);
int length = Convert.ToInt32(rsp.ContentLength);
byte[] buffer = new byte[length];
int rc = 0;
while ((rc = stream.Read(buffer, 0, length)) > 0)
{
outStream.Write(buffer, 0, rc);
}
outStream.Flush();
outStream.Close();
}
finally
{
// 释放资源
if (reader != null) reader.Close();
if (stream != null) stream.Close();
if (rsp != null) rsp.Close();
}
}
19
View Source File : HttpWebRequestResponseData.cs
License : MIT License
Project Creator : aliyunmq
License : MIT License
Project Creator : aliyunmq
public Stream OpenResponse()
{
if (_disposed)
throw new ObjectDisposedException("HttpWebResponseBody");
return _response.GetResponseStream();
}
19
View Source File : WebExtensions.cs
License : MIT License
Project Creator : aljazsim
License : MIT License
Project Creator : aljazsim
public static byte[] ExecuteBinaryRequest(this Uri uri, TimeSpan? timeout = null)
{
Stopwatch stopwatch;
byte[] responseContent;
Func<HttpWebResponse, byte[]> getDataFunc;
getDataFunc = (response) =>
{
int count;
List<byte> content = new List<byte>();
byte[] buffer = new byte[4096];
// download request contents into memory
using (Stream responseStream = response.GetResponseStream())
{
while ((count = responseStream.Read(buffer, 0, buffer.Length)) > 0)
{
content.AddRange(buffer.Take(count));
}
}
return content.ToArray();
};
stopwatch = Stopwatch.StartNew();
responseContent = uri.ExecuteRequest(getDataFunc, null, "text/plain", 0, timeout ?? TimeSpan.FromMinutes(1));
stopwatch.Stop();
return responseContent;
}
19
View Source File : NetMidiDownload.cs
License : GNU General Public License v2.0
Project Creator : AmanoTooko
License : GNU General Public License v2.0
Project Creator : AmanoTooko
public static string DownloadMidi(string id)
{
try
{
var request = (HttpWebRequest)WebRequest.Create(url+id);
request.Headers.Add("Accept-Encoding", "gzip,deflate");
var response = (HttpWebResponse)request.GetResponse();
using (GZipStream stream = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress))
{
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
var responseString = reader.ReadToEnd();
return responseString;
}
}
}
catch (Exception e)
{
Debug.WriteLine(e);
throw e;
}
}
See More Examples