Here are the examples of the csharp api System.Net.HttpWebRequest.GetResponse() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1384 Examples
19
Source : BitMexClient.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from 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
Source : BitStampClient.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
public void Connect()
{
if (string.IsNullOrWhiteSpace(_apiKeyPublic) ||
string.IsNullOrWhiteSpace(_apiKeySecret) ||
string.IsNullOrWhiteSpace(_clientId))
{
return;
}
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
// check server availability for HTTP communication with it / проверяем доступность сервера для HTTP общения с ним
Uri uri = new Uri("https://www.bitstamp.net");
try
{
HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(uri);
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
}
catch
{
LogMessageEvent("Сервер не доступен. Отсутствуюет интернет. ", LogMessageType.Error);
return;
}
IsConnected = true;
if (Connected != null)
{
Connected();
}
// start stream data through WebSocket / запускаем потоковые данные через WebSocket
_ws = new ClientWebSocket();
Uri wsUri = new Uri("wss://ws.bitstamp.net");
_ws.ConnectAsync(wsUri, CancellationToken.None).Wait();
if (_ws.State == WebSocketState.Open)
{
if (Connected != null)
{
Connected.Invoke();
}
IsConnected = true;
}
Thread worker = new Thread(GetRes);
worker.CurrentCulture = new CultureInfo("ru-RU");
worker.IsBackground = true;
worker.Start(_ws);
Thread converter = new Thread(Converter);
converter.CurrentCulture = new CultureInfo("ru-RU");
converter.IsBackground = true;
converter.Start();
}
19
Source : BybitRestRequestBuilder.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from 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
Source : RestRequestBuilder.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from 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
Source : RestRequestBuilder.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from 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
Source : KrakenRestApi.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from 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
Source : LivecoinClient.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
private string SendQuery(bool isAuth, string endPoint, string publicKey = "", string secretKey = "", string data = "")
{
string ResponseFromServer = "";
HttpStatusCode StatusCode;
string uri;
if (isAuth)
{
uri = _baseUri + endPoint;
}
else
{
uri = _baseUri + endPoint + data;
}
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
Stream dataStream;
if (isAuth)
{
string param = http_build_query(data);
string Sign = HashHMAC(secretKey, param).ToUpper();
request.Headers["Api-Key"] = publicKey;
request.Headers["Sign"] = Sign;
}
try
{
WebResponse WebResponse = request.GetResponse();
dataStream = WebResponse.GetResponseStream();
StreamReader StreamReader = new StreamReader(dataStream);
ResponseFromServer = StreamReader.ReadToEnd();
dataStream.Close();
WebResponse.Close();
StatusCode = HttpStatusCode.OK;
return ResponseFromServer;
}
catch (WebException ex)
{
if (ex.Response != null)
{
dataStream = ex.Response.GetResponseStream();
StreamReader StreamReader = new StreamReader(dataStream);
StatusCode = ((HttpWebResponse)ex.Response).StatusCode;
ResponseFromServer = ex.Message;
}
else
{
StatusCode = HttpStatusCode.ExpectationFailed;
ResponseFromServer = "Неизвестная ошибка";
}
return ResponseFromServer;
}
catch (Exception ex)
{
StatusCode = HttpStatusCode.ExpectationFailed;
ResponseFromServer = "Неизвестная ошибка";
return ResponseFromServer;
}
}
19
Source : KrakenRestApi.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from 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
Source : LivecoinClient.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
public void Connect()
{
if (string.IsNullOrEmpty(_pubKey) ||
string.IsNullOrEmpty(_secKey))
{
return;
}
string endPoint = "exchange/ticker?";
string param = "currencyPair=BTC/USD";
_isDisposed = false;
// check server availability for HTTP communication with it / проверяем доступность сервера для HTTP общения с ним
Uri uri = new Uri(_baseUri + endPoint + param);
try
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
var httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
}
catch (Exception exception)
{
SendLogMessage("Сервер не доступен. Отсутствует интернет " + exception.Message, LogMessageType.Error);
return;
}
Thread converter = new Thread(Converter);
converter.CurrentCulture = new CultureInfo("ru-RU");
converter.Name = "LivecoinConverterFread_" + _portfolioName;
converter.IsBackground = true;
converter.Start();
CreateNewWebSocket();
}
19
Source : RestChannel.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from 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
Source : ZBServer.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from 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
Source : RestChannel.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from 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
Source : main.cs
with GNU General Public License v3.0
from ALIILAPRO
with GNU General Public License v3.0
from 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
Source : main.cs
with GNU General Public License v3.0
from ALIILAPRO
with GNU General Public License v3.0
from 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
Source : WebUtils.cs
with Apache License 2.0
from alipay
with Apache License 2.0
from alipay
public string DoPost(string url, IDictionary<string, string> parameters, string charset)
{
HttpWebRequest req = GetWebRequest(url, "POST");
req.ContentType = "application/x-www-form-urlencoded;charset=" + charset;
byte[] postData = Encoding.GetEncoding(charset).GetBytes(BuildQuery(parameters, charset));
Stream reqStream = req.GetRequestStream();
reqStream.Write(postData, 0, postData.Length);
reqStream.Close();
HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
return GetResponsereplacedtring(rsp, encoding);
}
19
Source : WebUtils.cs
with Apache License 2.0
from alipay
with Apache License 2.0
from alipay
public string DoGet(string url, IDictionary<string, string> parameters, string charset)
{
if (parameters != null && parameters.Count > 0)
{
if (url.Contains("?"))
{
url = url + "&" + BuildQuery(parameters, charset);
}
else
{
url = url + "?" + BuildQuery(parameters, charset);
}
}
HttpWebRequest req = GetWebRequest(url, "GET");
req.ContentType = "application/x-www-form-urlencoded;charset=" + charset;
HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
return GetResponsereplacedtring(rsp, encoding);
}
19
Source : WebUtils.cs
with Apache License 2.0
from alipay
with Apache License 2.0
from alipay
public string DoPost(string url, IDictionary<string, string> textParams, IDictionary<string, FileItem> fileParams, string charset)
{
// 如果没有文件参数,则走普通POST请求
if (fileParams == null || fileParams.Count == 0)
{
return DoPost(url, textParams, charset);
}
string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
HttpWebRequest req = GetWebRequest(url, "POST");
req.ContentType = "multipart/form-data;charset=" + charset + ";boundary=" + boundary;
Stream reqStream = req.GetRequestStream();
byte[] itemBoundaryBytes = Encoding.GetEncoding(charset).GetBytes("\r\n--" + boundary + "\r\n");
byte[] endBoundaryBytes = Encoding.GetEncoding(charset).GetBytes("\r\n--" + boundary + "--\r\n");
// 组装文本请求参数
string textTemplate = "Content-Disposition:form-data;name=\"{0}\"\r\nContent-Type:text/plain\r\n\r\n{1}";
IEnumerator<KeyValuePair<string, string>> textEnum = textParams.GetEnumerator();
while (textEnum.MoveNext())
{
string textEntry = string.Format(textTemplate, textEnum.Current.Key, textEnum.Current.Value);
byte[] itemBytes = Encoding.GetEncoding(charset).GetBytes(textEntry);
reqStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
reqStream.Write(itemBytes, 0, itemBytes.Length);
}
// 组装文件请求参数
string fileTemplate = "Content-Disposition:form-data;name=\"{0}\";filename=\"{1}\"\r\nContent-Type:{2}\r\n\r\n";
IEnumerator<KeyValuePair<string, FileItem>> fileEnum = fileParams.GetEnumerator();
while (fileEnum.MoveNext())
{
string key = fileEnum.Current.Key;
FileItem fileItem = fileEnum.Current.Value;
string fileEntry = string.Format(fileTemplate, key, fileItem.GetFileName(), fileItem.GetMimeType());
byte[] itemBytes = Encoding.GetEncoding(charset).GetBytes(fileEntry);
reqStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
reqStream.Write(itemBytes, 0, itemBytes.Length);
byte[] fileBytes = fileItem.GetContent();
reqStream.Write(fileBytes, 0, fileBytes.Length);
}
reqStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
reqStream.Close();
HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
return GetResponsereplacedtring(rsp, encoding);
}
19
Source : AlipayMobilePublicMultiMediaClient.cs
with Apache License 2.0
from alipay
with Apache License 2.0
from alipay
private AopResponse DoGet(AopDictionary parameters, Stream outStream)
{
AlipayMobilePublicMultiMediaDownloadResponse response = null;
string url = this.serverUrl;
System.Console.WriteLine(url);
if (parameters != null && parameters.Count > 0)
{
if (url.Contains("?"))
{
url = url + "&" + WebUtils.BuildQuery(parameters, charset);
}
else
{
url = url + "?" + WebUtils.BuildQuery(parameters, charset);
}
}
HttpWebRequest req = webUtils.GetWebRequest(url, "GET");
req.ContentType = "application/x-www-form-urlencoded;charset=" + charset;
HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
if (rsp.StatusCode == HttpStatusCode.OK)
{
if (rsp.ContentType.ToLower().Contains("text/plain"))
{
Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
string body = webUtils.GetResponsereplacedtring(rsp, encoding);
IAopParser<AlipayMobilePublicMultiMediaDownloadResponse> tp = new AopJsonParser<AlipayMobilePublicMultiMediaDownloadResponse>();
response = tp.Parse(body, charset);
}
else
{
GetResponsereplacedtream(outStream, rsp);
response = new AlipayMobilePublicMultiMediaDownloadResponse();
}
}
return response;
}
19
Source : HttpWebRequestFactory.cs
with MIT License
from aliyunmq
with MIT License
from aliyunmq
public virtual IWebResponseData GetResponse()
{
try
{
var response = _request.GetResponse() as HttpWebResponse;
return new HttpWebRequestResponseData(response);
}
catch(WebException webException)
{
var errorResponse = webException.Response as HttpWebResponse;
if (errorResponse != null)
{
throw new HttpErrorResponseException(webException.Message,
webException,
new HttpWebRequestResponseData(errorResponse));
}
throw;
}
}
19
Source : WebExtensions.cs
with MIT License
from aljazsim
with MIT License
from aljazsim
private static T ExecuteRequest<T>(this Uri uri, Func<HttpWebResponse, T> getDataFunc, byte[] data = null, string requestContentType = "text/plain", int redirectCount = 0, TimeSpan? timeout = null)
{
HttpWebRequest request;
T responseContent = default(T);
int maxRedirects = 30;
string location = "Location";
uri.CannotBeNull();
getDataFunc.CannotBeNull();
requestContentType.CannotBeNullOrEmpty();
redirectCount.MustBeGreaterThanOrEqualTo(0);
// make request
request = HttpWebRequest.Create(uri) as HttpWebRequest;
request.Method = data == null ? "GET" : "POST";
request.KeepAlive = false;
request.ContentType = requestContentType;
request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
request.CookieContainer = new CookieContainer();
request.UserAgent = "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1300.0 Iron/23.0.1300.0 Safari/537.11";
request.AllowAutoRedirect = false;
request.Timeout = (int)(timeout == null ? TimeSpan.FromSeconds(10) : (TimeSpan)timeout).TotalMilliseconds;
// setup request contents
if (data != null)
{
request.ContentLength = data.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(data, 0, data.Length);
}
}
// get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
if (response.StatusCode == HttpStatusCode.Redirect)
{
if (redirectCount <= maxRedirects)
{
if (response.Headers.AllKeys.Contains(location) &&
response.Headers[location].IsNotNullOrEmpty())
{
if (Uri.TryCreate(response.Headers[location], UriKind.Absolute, out uri))
{
responseContent = uri.ExecuteRequest(getDataFunc, data, requestContentType, ++redirectCount);
}
}
}
}
else
{
responseContent = getDataFunc(response);
}
}
return responseContent;
}
19
Source : HelperMethods.cs
with GNU General Public License v3.0
from AM2R-Community-Developers
with GNU General Public License v3.0
from AM2R-Community-Developers
public static bool IsConnectedToInternet()
{
log.Info("Checking internet connection...");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://github.com");
HttpWebResponse response = null;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException)
{
log.Info("Internet connection failed.");
return false;
}
log.Info("Internet connection established!");
return true;
}
19
Source : NetMidiDownload.cs
with GNU General Public License v2.0
from AmanoTooko
with GNU General Public License v2.0
from 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;
}
}
19
Source : lyricPoster.cs
with GNU General Public License v2.0
from AmanoTooko
with GNU General Public License v2.0
from AmanoTooko
public static void PostJson(string text)
{
try
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create($"http://127.0.0.1:{port}/command");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write($"/s ♪ {text} ♪");
streamWriter.Flush();
streamWriter.Close();
}
httpWebRequest.GetResponse();
}
catch (Exception ex)
{
}
}
19
Source : WebUtil.cs
with MIT License
from AmazingDM
with MIT License
from AmazingDM
public static string DownloadString(HttpWebRequest req, out HttpWebResponse rep, string encoding = "UTF-8")
{
rep = (HttpWebResponse) req.GetResponse();
using var responseStream = rep.GetResponseStream();
using var streamReader = new StreamReader(responseStream, Encoding.GetEncoding(encoding));
return streamReader.ReadToEnd();
}
19
Source : LauncherUpdater.cs
with GNU General Public License v3.0
from AM2R-Community-Developers
with GNU General Public License v3.0
from AM2R-Community-Developers
public static void Main()
{
log.Info("Running update check...");
string version = VERSION.Replace(".", "");
//update section
//delete old files that have been left
if (File.Exists(CrossPlatformOperations.CURRENTPATH + "/AM2RLauncher.bak"))
{
log.Info("AM2RLauncher.bak detected. Removing file.");
File.Delete(CrossPlatformOperations.CURRENTPATH + "/AM2RLauncher.bak");
}
if (currentPlatform.IsWinForms && File.Exists(oldConfigPath))
{
log.Info(CrossPlatformOperations.LAUNCHERNAME + ".oldCfg detected. Removing file.");
File.Delete(oldConfigPath);
}
if (currentPlatform.IsWinForms && Directory.Exists(CrossPlatformOperations.CURRENTPATH + "/oldLib"))
{
log.Info("Old lib folder detected, removing folder.");
Directory.Delete(CrossPlatformOperations.CURRENTPATH + "/oldLib", true);
}
// Clean up old update libs
if (currentPlatform.IsWinForms && Directory.Exists(CrossPlatformOperations.CURRENTPATH + "/lib"))
{
foreach (FileInfo file in new DirectoryInfo(CrossPlatformOperations.CURRENTPATH + "/lib").GetFiles())
{
if (file.Name.EndsWith(".bak"))
file.Delete();
}
// Do the same for each subdir
foreach (DirectoryInfo dir in new DirectoryInfo(CrossPlatformOperations.CURRENTPATH + "/lib").GetDirectories())
{
foreach (FileInfo file in dir.GetFiles())
{
if (file.Name.EndsWith(".bak"))
file.Delete();
}
}
}
//check settings if autoUpdateLauncher is set to true
bool autoUpdate = bool.Parse(CrossPlatformOperations.ReadFromConfig("AutoUpdateLauncher"));
if (autoUpdate)
{
log.Info("AutoUpdate Launcher set to true!");
//this is supposed to fix the updater throwing an exception on windows 7 and earlier(?)
//see this for information: https://stackoverflow.com/questions/2859790/the-request-was-aborted-could-not-create-ssl-tls-secure-channel and https://stackoverflow.com/a/50977774
if (currentPlatform.IsWinForms)
{
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
}
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://github.com/AM2R-Community-Developers/AM2RLauncher/releases/latest");
HttpWebResponse response = null;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException)
{
log.Error("WebException caught! Displaying MessageBox.");
MessageBox.Show(Language.Text.NoInternetConnection);
return;
}
Uri realUri = response.ResponseUri;
string onlineVersion = realUri.AbsoluteUri.Substring(realUri.AbsoluteUri.LastIndexOf('/') + 1);
bool isCurrentVersionOutdated = false;
string[] localVersionArray = VERSION.Split('.');
string[] onlineVersionArray = onlineVersion.Split('.');
for (int i = 0; i < localVersionArray.Length; i++)
{
if (int.Parse(onlineVersionArray[i]) > int.Parse(localVersionArray[i]))
{
isCurrentVersionOutdated = true;
break;
}
}
if (isCurrentVersionOutdated)
{
log.Info("Current version (" + VERSION + ") is outdated! Initiating update for version " + onlineVersion + ".");
string tmpUpdatePath = CrossPlatformOperations.CURRENTPATH + "/tmpupdate/";
string zipPath = CrossPlatformOperations.CURRENTPATH + "/launcher.zip";
// Clean tmpupdate
if (Directory.Exists(tmpUpdatePath))
Directory.Delete(tmpUpdatePath);
if (!Directory.Exists(tmpUpdatePath))
Directory.CreateDirectory(tmpUpdatePath);
try
{
using (var client = new WebClient())
{
string platformSuffix = "";
if (currentPlatform.IsWinForms) platformSuffix = "_win";
else if (currentPlatform.IsGtk) platformSuffix = "_lin";
log.Info("Downloading https://github.com/AM2R-Community-Developers/AM2RLauncher/releases/latest/download/AM2RLauncher_" + onlineVersion + platformSuffix + ".zip to " + zipPath + ".");
client.DownloadFile("https://github.com/AM2R-Community-Developers/AM2RLauncher/releases/latest/download/AM2RLauncher_" + onlineVersion + platformSuffix + ".zip", zipPath);
log.Info("File successfully downloaded.");
}
}
catch(UnauthorizedAccessException)
{
log.Error("UnauthorizedAccessException caught! Displaying MessageBox.");
MessageBox.Show(Language.Text.UnauthorizedAccessMessage);
return;
}
ZipFile.ExtractToDirectory(zipPath, tmpUpdatePath);
log.Info("Updates successfully extracted to " + tmpUpdatePath);
File.Delete(zipPath);
File.Move(updatePath + "/" + CrossPlatformOperations.LAUNCHERNAME, CrossPlatformOperations.CURRENTPATH + "/AM2RLauncher.bak");
if (currentPlatform.IsWinForms) File.Move(CrossPlatformOperations.LAUNCHERNAME + ".config", CrossPlatformOperations.LAUNCHERNAME + ".oldCfg");
foreach (var file in new DirectoryInfo(tmpUpdatePath).GetFiles())
{
log.Info("Moving " + file.FullName + " to " + CrossPlatformOperations.CURRENTPATH + "/" + file.Name);
File.Copy(file.FullName, updatePath + "/" + file.Name, true);
}
// for windows, the actual application is in "AM2RLauncher.dll". Which means, we need to update the lib folder as well.
if (currentPlatform.IsWinForms && Directory.Exists(CrossPlatformOperations.CURRENTPATH + "/lib"))
{
// Directory.Move(CrossPlatformOperations.CURRENTPATH + "/lib", CrossPlatformOperations.CURRENTPATH + "/oldLib");
// So, because Windows behavior is dumb...
// Rename all files in lib to *.bak
foreach (FileInfo file in new DirectoryInfo(CrossPlatformOperations.CURRENTPATH + "/lib").GetFiles())
{
file.CopyTo(file.Directory + file.Name + ".bak");
}
// Do the same for each subdir
foreach(DirectoryInfo dir in new DirectoryInfo(CrossPlatformOperations.CURRENTPATH + "/lib").GetDirectories())
{
foreach (FileInfo file in dir.GetFiles())
{
file.CopyTo(file.Directory + file.Name + ".bak");
}
}
// Yes, the above calls could be recursive. No, I can't be bothered to make them as such.
HelperMethods.DirectoryCopy(tmpUpdatePath + "lib", CrossPlatformOperations.CURRENTPATH + "/lib", true);
}
Directory.Delete(tmpUpdatePath, true);
CrossPlatformOperations.CopyOldConfigToNewConfig();
log.Info("Files extracted. Preparing to restart executable...");
if (currentPlatform.IsGtk) System.Diagnostics.Process.Start("chmod", "+x ./AM2RLauncher.Gtk");
System.Diagnostics.Process.Start(updatePath + "/" + CrossPlatformOperations.LAUNCHERNAME);
Environment.Exit(0);
}
}
else
{
log.Info("AutoUpdate Launcher set to false. Exiting update check.");
}
}
19
Source : BuildDeployPortal.cs
with MIT License
from anderm
with MIT License
from anderm
public static bool UninstallApp(string packageFamilyName, ConnectInfo connectInfo)
{
try
{
// Find the app description
AppDetails appDetails = QueryAppDetails(packageFamilyName, connectInfo);
if (appDetails == null)
{
Debug.LogError(string.Format("Application '{0}' not found", packageFamilyName));
return false;
}
// Setup the command
string query = string.Format(kAPI_InstallQuery, connectInfo.IP);
query += "?package=" + WWW.EscapeURL(appDetails.PackageFullName);
// Use HttpWebRequest for a delete query
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(query);
request.Timeout = TimeoutMS;
request.Credentials = new NetworkCredential(connectInfo.User, connectInfo.Preplacedword);
request.Method = "DELETE";
using (HttpWebResponse httpResponse = (HttpWebResponse)request.GetResponse())
{
Debug.Log("Response = " + httpResponse.StatusDescription);
httpResponse.Close();
}
}
catch (System.Exception ex)
{
Debug.LogError(ex.ToString());
return false;
}
return true;
}
19
Source : BuildDeployPortal.cs
with MIT License
from anderm
with MIT License
from anderm
public static bool LaunchApp(string packageFamilyName, ConnectInfo connectInfo)
{
// Find the app description
AppDetails appDetails = QueryAppDetails(packageFamilyName, connectInfo);
if (appDetails == null)
{
Debug.LogError("Appliation not found");
return false;
}
// Setup the command
string query = string.Format(kAPI_AppQuery, connectInfo.IP);
query += "?appid=" + WWW.EscapeURL(EncodeTo64(appDetails.PackageRelativeId));
query += "&package=" + WWW.EscapeURL(EncodeTo64(appDetails.PackageFamilyName));
// Use HttpWebRequest
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(query);
request.Timeout = TimeoutMS;
request.Credentials = new NetworkCredential(connectInfo.User, connectInfo.Preplacedword);
request.Method = "POST";
// Query
using (HttpWebResponse httpResponse = (HttpWebResponse)request.GetResponse())
{
Debug.Log("Response = " + httpResponse.StatusDescription);
httpResponse.Close();
}
return true;
}
19
Source : BuildDeployPortal.cs
with MIT License
from anderm
with MIT License
from anderm
public static bool KillApp(string packageFamilyName, ConnectInfo connectInfo)
{
try
{
// Find the app description
AppDetails appDetails = QueryAppDetails(packageFamilyName, connectInfo);
if (appDetails == null)
{
Debug.LogError("Appliation not found");
return false;
}
// Setup the command
string query = string.Format(kAPI_AppQuery, connectInfo.IP);
query += "?package=" + WWW.EscapeURL(EncodeTo64(appDetails.PackageFullName));
// And send it across
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(query);
request.Timeout = TimeoutMS;
request.Credentials = new NetworkCredential(connectInfo.User, connectInfo.Preplacedword);
request.Method = "DELETE";
using (HttpWebResponse httpResponse = (HttpWebResponse)request.GetResponse())
{
Debug.Log("Response = " + httpResponse.StatusDescription);
httpResponse.Close();
}
}
catch (System.Exception ex)
{
Debug.LogError(ex.ToString());
return false;
}
return true;
}
19
Source : Networking.cs
with GNU General Public License v3.0
from anderson-joyle
with GNU General Public License v3.0
from anderson-joyle
protected string fetch(Uri uri)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri.AbsoluteUri);
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
ServicePointManager.SecurityProtocol =
SecurityProtocolType.Tls |
SecurityProtocolType.Tls11 |
SecurityProtocolType.Tls12 |
SecurityProtocolType.Ssl3;
string ret = string.Empty;
request.Method = "GET";
request.Accept = "application/json";
request.ContentLength = 0;
using (var response = request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader streamReader = new StreamReader(responseStream))
{
ret = streamReader.ReadToEnd();
}
}
}
return ret;
}
19
Source : GeoCodeAddress.cs
with MIT License
from AndrewButenko
with MIT License
from AndrewButenko
protected override void ExecuteWorkflowLogic()
{
if (string.IsNullOrWhiteSpace(Context.Settings.BingMapsKey))
throw new InvalidPluginExecutionException("BingMaps Key setting is not available.");
var address = Address.Get(Context.ExecutionContext);
if (string.IsNullOrWhiteSpace(address))
throw new InvalidPluginExecutionException("Address parameter is not available");
var url = $"http://dev.virtualearth.net/REST/v1/Locations?q={Uri.EscapeDataString(address)}&key={Context.Settings.BingMapsKey}";
string jsonResult = null;
var request = (HttpWebRequest)WebRequest.Create(url);
using (var resStream = new StreamReader(request.GetResponse().GetResponseStream()))
{
jsonResult = resStream.ReadToEnd();
}
var response = JsonConvert.DeserializeObject<Response>(jsonResult);
if (response.StatusCode != 200)
{
throw new InvalidPluginExecutionException($"BingMaps Endpoint call failed - {string.Join(Environment.NewLine, response.ErrorDetails)}{Environment.NewLine}{response.StatusDescription}");
}
var geocodePoint = response.ResourceSets.FirstOrDefault()?.Resources.FirstOrDefault()?.GeocodePoints
.FirstOrDefault();
if (geocodePoint == null)
{
IsResolved.Set(Context.ExecutionContext, false);
return;
}
IsResolved.Set(Context.ExecutionContext, true);
Lareplacedude.Set(Context.ExecutionContext, Convert.ToDecimal(geocodePoint.Coordinates[0]));
Longitude.Set(Context.ExecutionContext, Convert.ToDecimal(geocodePoint.Coordinates[1]));
}
19
Source : RefreshCurrencyExchangeRates.cs
with MIT License
from AndrewButenko
with MIT License
from AndrewButenko
protected override void ExecuteWorkflowLogic()
{
#region Get All Currencies From Endpoint and check that call was successfull
string jsonResult = null;
var url = "http://apilayer.net/api/live?access_key=" + Context.Settings.CurrencylayerKey;
var request = (HttpWebRequest)WebRequest.Create(url);
using (var resStream = new StreamReader(request.GetResponse().GetResponseStream()))
{
jsonResult = resStream.ReadToEnd();
}
var jobject = JObject.Parse(jsonResult);
var success = jobject.SelectToken("$.success").Value<bool>();
if (!success)
{
var errorToken = jobject.SelectToken("$.error");
var errorMessage = $@"Can't obtain currency exchange rates:
Code: {errorToken.SelectToken("code").Value<int>()}
Type: {errorToken.SelectToken("type").Value<string>()}
Info: {errorToken.SelectToken("info").Value<string>()}";
throw new InvalidPluginExecutionException(errorMessage);
}
#endregion Get All Currencies From Endpoint and check that call was successfull
#region Get Base Currency
QueryExpression query = new QueryExpression("transactioncurrency")
{
ColumnSet = new ColumnSet("isocurrencycode", "currencyname")
};
query.AddLink("organization", "transactioncurrencyid", "basecurrencyid", JoinOperator.Inner);
var baseCurrency = Context.SystemService.RetrieveMultiple(query).Enreplacedies.FirstOrDefault();
if (baseCurrency == null)
return;
var baseCurrencyCode = baseCurrency.GetAttributeValue<string>("isocurrencycode").ToUpper();
var baseCurrencyId = baseCurrency.Id;
var baseCurrencyName = baseCurrency.GetAttributeValue<string>("currencyname");
var baseCurrencyNode = jobject.SelectToken($"$.quotes.USD{baseCurrencyCode}");
if (baseCurrencyNode == null)
{
throw new InvalidPluginExecutionException($"Exchange Rates for your Base Currency ({baseCurrencyName}) are not available");
}
var usdToBaseCurrencyRate = baseCurrencyNode.Value<decimal>();
#endregion Get Base Currency
#region Getting All Currencies Except Base Currency
query = new QueryExpression("transactioncurrency")
{
ColumnSet = new ColumnSet("isocurrencycode", "currencyname")
};
query.Criteria.AddCondition("transactioncurrencyid", ConditionOperator.NotEqual, baseCurrencyId);
List<Enreplacedy> allCurrencies = Context.SystemService.RetrieveMultiple(query).Enreplacedies.ToList();
#endregion Getting All Currencies Except Base Currency
#region Looping through currencies and updating Exhange Rates
foreach (Enreplacedy currency in allCurrencies)
{
var currencyCode = currency.GetAttributeValue<string>("isocurrencycode").ToUpper();
var currencyName = currency.GetAttributeValue<string>("currencyname");
var currencyNode = jobject.SelectToken($"$.quotes.USD{currencyCode}");
if (currencyNode == null)
{
Context.TracingService.Trace($"Can't refresh exchange rate for {currencyName} currency");
continue;
}
var usdToCurrencyRate = currencyNode.Value<decimal>();
decimal rate = usdToCurrencyRate / usdToBaseCurrencyRate;
currency.Attributes.Clear();
currency["exchangerate"] = rate;
Context.SystemService.Update(currency);
}
#endregion Looping through currencies and updating Exhange Rates
}
19
Source : UpdateMonitor.cs
with GNU General Public License v3.0
from Angelinsky7
with GNU General Public License v3.0
from Angelinsky7
private Tuple<String, Boolean> GetFileVersion() {
String r = String.Empty;
try {
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(String.Format(UPDATE_URL, m_Rnd.Next(4000030, 504230420)));
request.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
using (Stream stream = response.GetResponseStream()) {
using (StreamReader reader = new StreamReader(stream)) {
r = reader.ReadToEnd();
}
}
}
} catch (Exception ex) {
r = ex.Message;
}
return new Tuple<String, Boolean>(r, true);
}
19
Source : HttpHelper.cs
with Apache License 2.0
from anjoy8
with Apache License 2.0
from anjoy8
public static async Task<string> GetAsync(string serviceAddress)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
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.UTF8);
string retString = await myStreamReader.ReadToEndAsync();
myStreamReader.Close();
myResponseStream.Close();
return retString;
}
19
Source : HttpHelper.cs
with Apache License 2.0
from anjoy8
with Apache License 2.0
from anjoy8
public static string Post(string serviceAddress, string strContent = null)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
request.Method = "POST";
request.ContentType = "application/json";
//判断有无POST内容
if (!string.IsNullOrWhiteSpace(strContent))
{
using (StreamWriter dataStream = new StreamWriter(request.GetRequestStream()))
{
dataStream.Write(strContent);
dataStream.Close();
}
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string encoding = response.ContentEncoding;
if (string.IsNullOrWhiteSpace(encoding))
{
encoding = "UTF-8"; //默认编码
}
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
string retString = reader.ReadToEnd();
return retString;
}
19
Source : HttpHelper.cs
with Apache License 2.0
from anjoy8
with Apache License 2.0
from anjoy8
public static string Get(string serviceAddress)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
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.UTF8);
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
return retString;
}
19
Source : HttpHelper.cs
with Apache License 2.0
from anjoy8
with Apache License 2.0
from anjoy8
public static async Task<string> PostAsync(string serviceAddress, string strContent = null)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
request.Method = "POST";
request.ContentType = "application/json";
//判断有无POST内容
if (!string.IsNullOrWhiteSpace(strContent))
{
using (StreamWriter dataStream = new StreamWriter(request.GetRequestStream()))
{
dataStream.Write(strContent);
dataStream.Close();
}
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string encoding = response.ContentEncoding;
if (string.IsNullOrWhiteSpace(encoding))
{
encoding = "UTF-8"; //默认编码
}
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
string retString = await reader.ReadToEndAsync();
return retString;
}
19
Source : PayServices.cs
with Apache License 2.0
from anjoy8
with Apache License 2.0
from anjoy8
public async Task<MessageModel<PayRefundReturnResultModel>> PayRefund(PayRefundNeedModel payModel)
{
_logger.LogInformation("退款开始");
MessageModel<PayRefundReturnResultModel> messageModel = new MessageModel<PayRefundReturnResultModel>();
messageModel.response = new PayRefundReturnResultModel();
try
{
_logger.LogInformation($"原始GET参数->{_httpContextAccessor.HttpContext.Request.QueryString}");
string REQUEST_SN = StringHelper.GetGuidToLongID().ToString().Substring(0, 16);//请求序列码
string CUST_ID = StaticPayInfo.MERCHANTID;//商户号
string USER_ID = StaticPayInfo.USER_ID;//操作员号
string PreplacedWORD = StaticPayInfo.PreplacedWORD;//密码
string TX_CODE = "5W1004";//交易码
string LANGUAGE = "CN";//语言
//string SIGN_INFO = "";//签名信息
//string SIGNCERT = "";//签名CA信息
//外联平台客户端服务部署的地址+设置的监听端口
string sUrl = StaticPayInfo.OutAddress;
//XML请求报文
//string sRequestMsg = $" requestXml=<?xml version=\"1.0\" encoding=\"GB2312\" standalone=\"yes\" ?><TX><REQUEST_SN>{REQUEST_SN}</REQUEST_SN><CUST_ID>{CUST_ID}</CUST_ID><USER_ID>{USER_ID}</USER_ID><PreplacedWORD>{PreplacedWORD}</PreplacedWORD><TX_CODE>{TX_CODE}</TX_CODE><LANGUAGE>{LANGUAGE}</LANGUAGE><TX_INFO><MONEY>{payModel.MONEY}</MONEY><ORDER>{payModel.ORDER}</ORDER><REFUND_CODE>{payModel.REFUND_CODE}</REFUND_CODE></TX_INFO><SIGN_INFO></SIGN_INFO><SIGNCERT></SIGNCERT></TX> ";
string sRequestMsg = $"<?xml version=\"1.0\" encoding=\"GB2312\" standalone=\"yes\" ?><TX><REQUEST_SN>{REQUEST_SN}</REQUEST_SN><CUST_ID>{CUST_ID}</CUST_ID><USER_ID>{USER_ID}</USER_ID><PreplacedWORD>{PreplacedWORD}</PreplacedWORD><TX_CODE>{TX_CODE}</TX_CODE><LANGUAGE>{LANGUAGE}</LANGUAGE><TX_INFO><MONEY>{payModel.MONEY}</MONEY><ORDER>{payModel.ORDER}</ORDER><REFUND_CODE>{payModel.REFUND_CODE}</REFUND_CODE></TX_INFO><SIGN_INFO></SIGN_INFO><SIGNCERT></SIGNCERT></TX> ";
//string sRequestMsg = readRequestFile("E:/02-外联平台/06-测试/测试报文/商户网银/客户端连接-5W1001-W06.txt");
//注意:请求报文必须放在requestXml参数送
sRequestMsg = "requestXml=" + sRequestMsg;
_logger.LogInformation("请求地址:" + sUrl);
_logger.LogInformation("请求报文:" + sRequestMsg);
HttpWebRequest request = (System.Net.HttpWebRequest)HttpWebRequest.Create(sUrl);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.KeepAlive = false;
request.Connection = "";
//外联平台使用GB18030编码,这里进行转码处理
byte[] byteRquest = Encoding.GetEncoding("GB18030").GetBytes(sRequestMsg);
request.ContentLength = byteRquest.Length;
//发送请求
Stream writerStream = request.GetRequestStream();
await writerStream.WriteAsync(byteRquest, 0, byteRquest.Length);
writerStream.Flush();
writerStream.Close();
//接收请求
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream result = response.GetResponseStream();
StreamReader readerResult = new StreamReader(result, System.Text.Encoding.GetEncoding("GB18030"));
string sResult = await readerResult.ReadToEndAsync();
_logger.LogInformation("响应报文:" + sResult);
var Xmlresult = XmlHelper.ParseFormByXml<PayRefundReturnModel>(sResult, "TX");
if (Xmlresult.RETURN_CODE.Equals("000000"))
{
messageModel.success = true;
messageModel.msg = "退款成功";
}
else
{
messageModel.success = false;
messageModel.msg = "退款失败";
}
messageModel.response.RETURN_MSG = Xmlresult.RETURN_MSG;
messageModel.response.TX_CODE = Xmlresult.TX_CODE;
messageModel.response.REQUEST_SN = Xmlresult.REQUEST_SN;
messageModel.response.RETURN_CODE = Xmlresult.RETURN_CODE;
messageModel.response.CUST_ID = Xmlresult.CUST_ID;
messageModel.response.LANGUAGE = Xmlresult.LANGUAGE;
messageModel.response.AMOUNT = Xmlresult.TX_INFO?.AMOUNT;
messageModel.response.PAY_AMOUNT = Xmlresult.TX_INFO?.PAY_AMOUNT;
messageModel.response.ORDER_NUM = Xmlresult.TX_INFO?.ORDER_NUM;
}
catch (Exception ex)
{
messageModel.success = false;
messageModel.msg = "服务错误";
messageModel.response.RETURN_MSG = ex.Message;
_logger.LogInformation($"异常信息:{ex.Message}");
_logger.LogInformation($"异常堆栈:{ex.StackTrace}");
}
finally
{
_logger.LogInformation($"返回数据->{JsonHelper.GetJSON<MessageModel<PayRefundReturnResultModel>>(messageModel)}");
_logger.LogInformation("退款结束");
}
return messageModel;
}
19
Source : GetNetData.cs
with Apache License 2.0
from anjoy8
with Apache License 2.0
from anjoy8
public static string Get(string serviceAddress)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
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.UTF8);
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
return retString;
}
19
Source : GetNetData.cs
with Apache License 2.0
from anjoy8
with Apache License 2.0
from anjoy8
public static string Post(string serviceAddress)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
request.Method = "POST";
request.ContentType = "application/json";
string strContent = @"{ ""mmmm"": ""89e"",""nnnnnn"": ""0101943"",""kkkkkkk"": ""e8sodijf9""}";
using (StreamWriter dataStream = new StreamWriter(request.GetRequestStream()))
{
dataStream.Write(strContent);
dataStream.Close();
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string encoding = response.ContentEncoding;
if (encoding == null || encoding.Length < 1)
{
encoding = "UTF-8"; //默认编码
}
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
string retString = reader.ReadToEnd();
return retString;
//解析josn
//JObject jo = JObject.Parse(retString);
//Response.Write(jo["message"]["mmmm"].ToString());
}
19
Source : HttpSignaling.cs
with Apache License 2.0
from araobp
with Apache License 2.0
from araobp
private static HttpWebResponse HTTPGetResponse(HttpWebRequest request)
{
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
return response;
}
else
{
Debug.LogError($"Signaling: {response.ResponseUri} HTTP request failed ({response.StatusCode})");
response.Close();
}
}
catch (Exception e)
{
Debug.LogError("Signaling: HTTP request error " + e);
}
return null;
}
19
Source : RequestClient.cs
with Apache License 2.0
from arbing
with Apache License 2.0
from arbing
public string Send(string requestUri, object queryObj, object bodyObj = null,
HttpMethod method = HttpMethod.GET)
{
if (string.IsNullOrEmpty(requestUri))
{
throw new ArgumentException("requestUri");
}
if (method == HttpMethod.GET && bodyObj != null)
{
throw new InvalidOperationException("Get request cant't contain body");
}
IDictionary<string, string> parameters = new Dictionary<string, string>();
if (queryObj != null)
{
var jobj = JObject.FromObject(queryObj);
foreach (var property in jobj.Properties())
{
var jvalue = property.Value as JValue;
if (jvalue != null && jvalue.Value != null)
{
parameters[property.Name] = property.Value.ToString();
}
}
}
if (parameters.Count > 0)
{
var queryToAppend = "?" + string.Join("&",
parameters.Select(kvp => string.Format("{0}={1}", kvp.Key, kvp.Value)));
requestUri += queryToAppend;
}
var body = "";
if (bodyObj != null)
{
body = JsonConvert.SerializeObject(bodyObj);
}
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);
request.Timeout = 10 * 1000;
request.Method = method.ToString().ToUpper();
request.ContentType = "application/json;charset=UTF-8";
if (method != HttpMethod.GET && !string.IsNullOrEmpty(body))
{
var encoding = Encoding.UTF8;
if (!string.IsNullOrEmpty(body))
{
byte[] buffer = encoding.GetBytes(body);
using (Stream stream = request.GetRequestStream())
{
stream.Write(buffer, 0, buffer.Length);
}
}
}
var requestId = Guid.NewGuid();
HttpWebResponse response = null;
string responseTxt = null;
try
{
// 请求前打印请求信息
if (DumpRequest != null)
{
DumpRequest(new
{
RequestId = requestId,
Type = "Request",
Uri = request.RequestUri,
request.Method,
request.ContentType,
Content = body
});
}
response = (HttpWebResponse)request.GetResponse();
// 请求返回正常
responseTxt = ReadResponseStream(response);
// 请求返回后打印响应信息
if (DumpRequest != null)
{
DumpRequest(new
{
RequestId = requestId,
Type = "Response",
Uri = response.ResponseUri,
response.Method,
response.ContentType,
Content = responseTxt
});
}
}
catch (WebException webEx)
{
// 请求异常打印响应信息
if (DumpRequest != null)
{
DumpRequest(new
{
RequestId = requestId,
Type = "Error",
Uri = request.RequestUri,
Status = webEx.Status.ToString(),
webEx.Message,
});
}
var res = new JsonResult { errcode = ReturnCode.系统繁忙, errmsg = webEx.Message };
responseTxt = JsonConvert.SerializeObject(res);
}
return responseTxt;
}
19
Source : RequestClient.cs
with Apache License 2.0
from arbing
with Apache License 2.0
from arbing
public string Send(string requestUri, object queryObj, object bodyObj = null, string authorization = null,
HttpMethod method = HttpMethod.GET)
{
if (string.IsNullOrEmpty(requestUri))
{
throw new ArgumentException("requestUri");
}
if (method == HttpMethod.GET && bodyObj != null)
{
throw new InvalidOperationException("Get request cant't contain body");
}
IDictionary<string, string> parameters = new Dictionary<string, string>();
if (queryObj != null)
{
var jobj = JObject.FromObject(queryObj);
foreach (var property in jobj.Properties())
{
var jvalue = property.Value as JValue;
if (jvalue != null && jvalue.Value != null)
{
parameters[property.Name] = property.Value.ToString();
}
}
}
if (parameters.Count > 0)
{
var queryToAppend = "?" + string.Join("&",
parameters.Select(kvp => string.Format("{0}={1}", kvp.Key, kvp.Value)));
requestUri += queryToAppend;
}
var body = "";
if (bodyObj != null)
{
body = JsonConvert.SerializeObject(bodyObj);
}
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(requestUri);
request.Method = method.ToString().ToUpper();
request.ContentType = "text/json";
if (!string.IsNullOrEmpty(authorization))
{
request.Headers.Add(HttpRequestHeader.Authorization, authorization);
}
if (method != HttpMethod.GET && !string.IsNullOrEmpty(body))
{
var encoding = Encoding.UTF8;
if (!string.IsNullOrEmpty(body))
{
byte[] buffer = encoding.GetBytes(body);
request.ContentLength = buffer.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(buffer, 0, buffer.Length);
}
}
}
var requestId = Guid.NewGuid();
HttpWebResponse response = null;
string responseTxt = null;
try
{
// 请求前打印请求信息
if (DumpRequest != null)
{
DumpRequest(new
{
Type = "Request",
Id = requestId,
Uri = request.RequestUri,
request.Method,
request.ContentType,
Authorization = authorization,
Content = body
}, "Request");
}
response = (HttpWebResponse) request.GetResponse();
// 请求返回正常
responseTxt = ReadResponseStream(response);
// 请求返回后打印响应信息
if (DumpRequest != null)
{
DumpRequest(new
{
Type = "Response",
Id = requestId,
Uri = request.RequestUri,
response.ContentType,
Content = responseTxt
}, "Response");
}
}
catch (WebException webEx)
{
response = webEx.Response as HttpWebResponse;
if (response != null)
{
var content = ReadResponseStream(response);
// 请求异常打印响应信息
if (DumpRequest != null)
{
DumpRequest(new
{
Type = "Error",
Id = requestId,
Uri = request.RequestUri,
Status = webEx.Status.ToString(),
webEx.Message,
Content = content
}, "Error");
}
responseTxt =
JsonConvert.SerializeObject(
new JsonResult
{
errorcode = (ReturnCode) (int) response.StatusCode,
errormsg = webEx.Message
});
}
else
{
// 请求异常打印响应信息
if (DumpRequest != null)
{
DumpRequest(new
{
Type = "Error",
Id = requestId,
Uri = request.RequestUri,
Status = webEx.Status.ToString(),
webEx.Message,
}, "Error");
}
responseTxt =
JsonConvert.SerializeObject(
new JsonResult {errorcode = ReturnCode.系统繁忙, errormsg = webEx.Message});
}
}
return responseTxt;
}
19
Source : RequestClient.cs
with Apache License 2.0
from arbing
with Apache License 2.0
from arbing
public string Send(string requestUri, object queryObj, object bodyObj = null,
HttpMethod method = HttpMethod.GET)
{
if (string.IsNullOrEmpty(requestUri))
{
throw new ArgumentException("requestUri");
}
if (method == HttpMethod.GET && bodyObj != null)
{
throw new InvalidOperationException("Get request cant't contain body");
}
IDictionary<string, string> parameters = new Dictionary<string, string>();
if (queryObj != null)
{
var jobj = JObject.FromObject(queryObj);
foreach (var property in jobj.Properties())
{
var jvalue = property.Value as JValue;
if (jvalue != null && jvalue.Value != null)
{
parameters[property.Name] = property.Value.ToString();
}
}
}
if (parameters.Count > 0)
{
var queryToAppend = "?" + string.Join("&",
parameters.Select(kvp => string.Format("{0}={1}", kvp.Key, kvp.Value)));
requestUri += queryToAppend;
}
var body = "";
if (bodyObj != null)
{
body = JsonConvert.SerializeObject(bodyObj);
}
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(requestUri);
request.Timeout = 10 * 1000;
request.Method = method.ToString().ToUpper();
request.ContentType = "application/json;charset=UTF-8";
if (method != HttpMethod.GET && !string.IsNullOrEmpty(body))
{
var encoding = Encoding.UTF8;
if (!string.IsNullOrEmpty(body))
{
byte[] buffer = encoding.GetBytes(body);
using (Stream stream = request.GetRequestStream())
{
stream.Write(buffer, 0, buffer.Length);
}
}
}
var requestId = Guid.NewGuid();
HttpWebResponse response = null;
string responseTxt = null;
try
{
// 请求前打印请求信息
if (DumpRequest != null)
{
DumpRequest(new
{
Type = "Request",
Id = requestId,
Uri = request.RequestUri,
request.Method,
request.ContentType,
Content = body
}, "Request");
}
response = (HttpWebResponse) request.GetResponse();
// 请求返回正常
responseTxt = ReadResponseStream(response);
// 请求返回后打印响应信息
if (DumpRequest != null)
{
DumpRequest(new
{
Type = "Response",
Id = requestId,
Uri = request.RequestUri,
response.ContentType,
Content = responseTxt
}, "Response");
}
}
catch (WebException webEx)
{
// 请求异常打印响应信息
if (DumpRequest != null)
{
DumpRequest(new
{
Type = "Error",
Id = requestId,
Uri = request.RequestUri,
Status = webEx.Status.ToString(),
webEx.Message,
}, "Error");
}
var res = new JsonResult {errcode = ReturnCode.系统繁忙, errmsg = webEx.Message};
responseTxt = JsonConvert.SerializeObject(res);
}
return responseTxt;
}
19
Source : RequestUtility.cs
with Apache License 2.0
from arbing
with Apache License 2.0
from arbing
internal static string Send(string requestUri, object queryObj, object bodyObj = null,
HttpMethod method = HttpMethod.GET)
{
if (string.IsNullOrEmpty(requestUri))
{
throw new ArgumentException("requestUri");
}
if (method == HttpMethod.GET && bodyObj != null)
{
throw new InvalidOperationException("Get request cant't contain body");
}
IDictionary<string, string> parameters = new Dictionary<string, string>();
if (queryObj != null)
{
var jobj = JObject.FromObject(queryObj);
foreach (var property in jobj.Properties())
{
var jvalue = property.Value as JValue;
if (jvalue != null && jvalue.Value != null)
{
parameters[property.Name] = property.Value.ToString();
}
}
}
if (parameters.Count > 0)
{
var queryToAppend = "?" + string.Join("&",
parameters.Select(kvp => string.Format("{0}={1}", kvp.Key, kvp.Value)));
requestUri += queryToAppend;
}
var body = "";
if (bodyObj != null)
{
body = JsonConvert.SerializeObject(bodyObj);
}
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(requestUri);
request.Method = method.ToString().ToUpper();
request.ContentType = "application/json;charset=UTF-8";
if (method != HttpMethod.GET && !string.IsNullOrEmpty(body))
{
var encoding = Encoding.UTF8;
if (!string.IsNullOrEmpty(body))
{
byte[] buffer = encoding.GetBytes(body);
using (Stream stream = request.GetRequestStream())
{
stream.Write(buffer, 0, buffer.Length);
}
}
}
try
{
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
// 请求返回正常
var txt = ReadResponseStream(response);
return txt;
}
catch (WebException webEx)
{
var response = (HttpWebResponse) webEx.Response;
if (response != null)
{
var txt = ReadResponseStream(response);
return txt;
}
else
{
return "{}";
}
}
}
19
Source : QRParser.cs
with MIT License
from architdate
with MIT License
from architdate
public Image getQRData()
{
byte[] data = Encoding.ASCII.GetBytes("savedataId=" + sID + "&battleTeamCd=" + tID);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://3ds.pokemon-gl.com/frontendApi/battleTeam/getQr");
request.Method = "POST";
request.Accept = "*/*";
request.Headers["Accept-Encoding"] = "gzip, deflate, br";
request.Headers["Accept-Language"] = "en-US,en;q=0.8";
request.KeepAlive = true;
request.ContentLength = 73;
request.ContentType = "application/x-www-form-urlencoded";
request.Headers["Cookie"] = cookie;
request.Host = "3ds.pokemon-gl.com";
request.Headers["Origin"] = "https://3ds.pokemon-gl.com/";
request.Referer = "https://3ds.pokemon-gl.com/rentalteam/" + tID;
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36";
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
using (WebResponse response = request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
//add failing validation.
try
{
return Image.FromStream(stream);
}
catch (Exception e)
{
//invalid QR
return null;
}
}
}
}
19
Source : URLGenning.cs
with MIT License
from architdate
with MIT License
from architdate
private string GetText(string url)
{
try
{
var request = (HttpWebRequest)WebRequest.Create(url);
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
return responseString;
}
catch(Exception e)
{
WinFormsUtil.Alert("An error occured while trying to obtain the contents of the URL. This is most likely an issue with your Internet Connection. The exact error is as follows: " + e.ToString());
return "Error :" + e.ToString();
}
}
19
Source : AutomaticLegality.cs
with MIT License
from architdate
with MIT License
from architdate
public static string GetPage(string url)
{
try
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.UserAgent = "AutoLegalityMod";
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
return responseString;
}
catch (Exception e)
{
Debug.WriteLine("An error occured while trying to obtain the contents of the URL. This is most likely an issue with your Internet Connection. The exact error is as follows: " + e.ToString() + "\nURL tried to access: " + url);
return "Error :" + e.ToString();
}
}
19
Source : NetUtil.cs
with MIT License
from architdate
with MIT License
from architdate
private static Stream GetStreamFromURL(string url)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
// The GitHub API will fail if no user agent is provided
httpWebRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36";
var httpWebResponse = httpWebRequest.GetResponse();
return httpWebResponse.GetResponseStream();
}
19
Source : QRParser.cs
with MIT License
from architdate
with MIT License
from architdate
public static Image GetQRData(string SaveID, string TeamID, string Cookie)
{
byte[] data = Encoding.ASCII.GetBytes($"savedataId={SaveID}&battleTeamCd={TeamID}");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://3ds.pokemon-gl.com/frontendApi/battleTeam/getQr");
request.Method = "POST";
request.Accept = "*/*";
request.Headers["Accept-Encoding"] = "gzip, deflate, br";
request.Headers["Accept-Language"] = "en-US,en;q=0.8";
request.KeepAlive = true;
request.ContentLength = 73;
request.ContentType = "application/x-www-form-urlencoded";
request.Headers["Cookie"] = Cookie;
request.Host = "3ds.pokemon-gl.com";
request.Headers["Origin"] = "https://3ds.pokemon-gl.com/";
request.Referer = $"https://3ds.pokemon-gl.com/rentalteam/{TeamID}";
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36";
using (Stream reqStream = request.GetRequestStream())
reqStream.Write(data, 0, data.Length);
using var response = request.GetResponse();
using var stream = response.GetResponseStream();
if (stream == null)
return null;
//add failing validation.
try
{
return Image.FromStream(stream);
}
#pragma warning disable CA1031 // Do not catch general exception types
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
//invalid QR
return null;
}
#pragma warning restore CA1031 // Do not catch general exception types
}
19
Source : MGDBDownloader.cs
with MIT License
from architdate
with MIT License
from architdate
public static string DownloadString(string address)
{
using (WebClient client = new WebClient())
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.github.com/repos/projectpokemon/EventsGallery/releases/latest");
request.Method = "GET";
request.UserAgent = "PKHeX-Auto-Legality-Mod";
request.Accept = "application/json";
WebResponse response = request.GetResponse(); //Error Here
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string result = reader.ReadToEnd();
return result;
}
}
See More Examples