Here are the examples of the csharp api System.Net.HttpWebRequest.GetRequestStream() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
584 Examples
19
Source : HttpClient.cs
with GNU Affero General Public License v3.0
from 3drepo
with GNU Affero General Public License v3.0
from 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
Source : Utility.Http.cs
with MIT License
from 7Bytes-Studio
with MIT License
from 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
Source : HTTP.cs
with MIT License
from 944095635
with MIT License
from 944095635
private void SetPostData(HttpItem item)
{
//验证在得到结果时是否有传入数据
if (!request.Method.Trim().ToLower().Contains("get"))
{
if (item.PostEncoding != null)
{
postencoding = item.PostEncoding;
}
byte[] buffer = null;
//写入Byte类型
if (item.PostDataType == PostDataType.Byte && item.PostdataByte != null && item.PostdataByte.Length > 0)
{
//验证在得到结果时是否有传入数据
buffer = item.PostdataByte;
}//写入文件
else if (item.PostDataType == PostDataType.FilePath && !string.IsNullOrWhiteSpace(item.Postdata))
{
StreamReader r = new StreamReader(item.Postdata, postencoding);
buffer = postencoding.GetBytes(r.ReadToEnd());
r.Close();
} //写入字符串
else if (!string.IsNullOrWhiteSpace(item.Postdata))
{
buffer = postencoding.GetBytes(item.Postdata);
}
if (buffer != null)
{
request.ContentLength = buffer.Length;
request.GetRequestStream().Write(buffer, 0, buffer.Length);
}
else
{
request.ContentLength = 0;
}
}
}
19
Source : BTCChinaAPI.cs
with MIT License
from aabiryukov
with MIT License
from aabiryukov
private string DoMethod(NameValueCollection jParams)
{
const int RequestTimeoutMilliseconds = 2*1000; // 2 sec
string tempResult = "";
try
{
lock (m_tonceLock)
{
//get tonce
TimeSpan timeSpan = DateTime.UtcNow - genesis;
long milliSeconds = Convert.ToInt64(timeSpan.TotalMilliseconds*1000);
jParams[pTonce] = Convert.ToString(milliSeconds, CultureInfo.InvariantCulture);
//mock json request id
jParams[pId] = jsonRequestID.Next().ToString(CultureInfo.InvariantCulture);
//build http head
string paramsHash = GetHMACSHA1Hash(jParams);
string base64String = Convert.ToBase64String(Encoding.ASCII.GetBytes(accessKey + ':' + paramsHash));
string postData = "{\"method\": \"" + jParams[pMethod] + "\", \"params\": [" + jParams[pParams] + "], \"id\": " +
jParams[pId] + "}";
//get webrequest,respawn new object per call for multiple connections
var webRequest = (HttpWebRequest) WebRequest.Create(url);
webRequest.Timeout = RequestTimeoutMilliseconds;
var bytes = Encoding.ASCII.GetBytes(postData);
webRequest.Method = jParams[pRequestMethod];
webRequest.ContentType = "application/json-rpc";
webRequest.ContentLength = bytes.Length;
webRequest.Headers["Authorization"] = "Basic " + base64String;
webRequest.Headers["Json-Rpc-Tonce"] = jParams[pTonce];
// Send the json authentication post request
using (var dataStream = webRequest.GetRequestStream())
{
dataStream.Write(bytes, 0, bytes.Length);
}
// Get authentication response
using (var response = webRequest.GetResponse())
{
using (var stream = response.GetResponseStream())
{
// ReSharper disable once replacedignNullToNotNullAttribute
using (var reader = new StreamReader(stream))
{
tempResult = reader.ReadToEnd();
}
}
}
}
}
catch (WebException ex)
{
throw new BTCChinaException(jParams[pMethod], jParams[pId], ex.Message, ex);
}
//there are two kinds of API response, result or error.
if (tempResult.IndexOf("result", StringComparison.Ordinal) < 0)
{
throw new BTCChinaException(jParams[pMethod], jParams[pId], "API error:\n" + tempResult);
}
//compare response id with request id and remove it from result
try
{
int cutoff = tempResult.LastIndexOf(':') + 2;//"id":"1"} so (last index of ':')+2=length of cutoff=start of id-string
string idString = tempResult.Substring(cutoff, tempResult.Length - cutoff - 2);//2=last "}
if (idString != jParams[pId])
{
throw new BTCChinaException(jParams[pMethod], jParams[pId], "JSON-request id is not equal with JSON-response id.");
}
else
{
//remove json request id from response json string
int fromComma = tempResult.LastIndexOf(',');
int toLastBrace = tempResult.Length - 1;
tempResult = tempResult.Remove(fromComma, toLastBrace - fromComma);
}
}
catch (ArgumentOutOfRangeException ex)
{
throw new BTCChinaException(jParams[pMethod], jParams[pId], "Argument out of range in parsing JSON response id:" + ex.Message, ex);
}
return tempResult;
}
19
Source : SoapSearch.cs
with MIT License
from ABN-SFLookupTechnicalSupport
with MIT License
from ABN-SFLookupTechnicalSupport
private static void Send(HttpWebRequest webRequest, string soapMessage) {
StreamWriter StreamWriter;
StreamWriter = new StreamWriter(webRequest.GetRequestStream());
StreamWriter.Write(soapMessage);
StreamWriter.Flush();
StreamWriter.Close();
}
19
Source : ConsultaExtensions.cs
with MIT License
from ACBrNet
with MIT License
from ACBrNet
internal static string SendPost(this HttpWebRequest request, Dictionary<string, string> postData, Encoding enconde)
{
request.Method = "POST";
var post = new StringBuilder();
var lastKey = postData.Last().Key;
foreach (var postValue in postData)
{
post.Append($"{postValue.Key}={postValue.Value}");
if (postValue.Key != lastKey) post.Append("&");
}
var byteArray = enconde.GetBytes(post.ToString());
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
var dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
var response = request.GetResponse();
var responseStream = response.GetResponseStream();
Guard.Against<ACBrException>(responseStream == null, "Erro ao acessar o site.");
string retorno;
using (var stHtml = new StreamReader(responseStream, enconde))
retorno = stHtml.ReadToEnd();
return retorno;
}
19
Source : CorreiosWebservice.cs
with MIT License
from ACBrNet
with MIT License
from ACBrNet
public override ACBrEndereco[] BuscarPorCEP(string cep)
{
try
{
var request = (HttpWebRequest)WebRequest.Create(CORREIOS_URL);
request.ProtocolVersion = HttpVersion.Version10;
request.UserAgent = "Mozilla/4.0 (compatible; Synapse)";
request.Method = "POST";
var postData = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" +
"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" " +
"xmlns:cli=\"http://cliente.bean.master.sigep.bsb.correios.com.br/\"> " +
" <soapenv:Header/>" +
" <soapenv:Body>" +
" <cli:consultaCEP>" +
" <cep>" + cep.OnlyNumbers() + "</cep>" +
" </cli:consultaCEP>" +
" </soapenv:Body>" +
" </soapenv:Envelope>";
var byteArray = Encoding.UTF8.GetBytes(postData);
var dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
string retorno;
// ReSharper disable once replacedignNullToNotNullAttribute
using (var stHtml = new StreamReader(request.GetResponse().GetResponseStream(), ACBrEncoding.ISO88591))
retorno = stHtml.ReadToEnd();
var doc = XDoreplacedent.Parse(retorno);
var element = doc.ElementAnyNs("Envelope").ElementAnyNs("Body").ElementAnyNs("consultaCEPResponse").ElementAnyNs("return");
var endereco = new ACBrEndereco();
endereco.CEP = element.Element("cep").GetValue<string>();
endereco.Bairro = element.Element("bairro").GetValue<string>();
endereco.Municipio = element.Element("cidade").GetValue<string>();
endereco.Complemento = $"{element.Element("complemento").GetValue<string>()}{Environment.NewLine}{element.Element("complemento2").GetValue<string>()}";
endereco.Logradouro = element.Element("end").GetValue<string>();
endereco.UF = (ConsultaUF)Enum.Parse(typeof(ConsultaUF), element.Element("uf").GetValue<string>());
endereco.TipoLogradouro = endereco.Logradouro.Split(' ')[0];
endereco.Logradouro = endereco.Logradouro.SafeReplace(endereco.TipoLogradouro, string.Empty);
return new[] { endereco };
}
catch (Exception exception)
{
throw new ACBrException(exception, "Erro ao consulta CEP.");
}
}
19
Source : APIConsumerHelper.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence
with BSD 3-Clause "New" or "Revised" License
from 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
Source : Requestor.cs
with MIT License
from adoprog
with MIT License
from 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
Source : SendToFlow.cs
with MIT License
from adoprog
with MIT License
from 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
Source : PaypalHelper.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public WebResponse GetPaymentWebResponse(string incomingReqStr)
{
var newReq = (HttpWebRequest)WebRequest.Create(PayPalBaseUrl);
//Set values for the request back
newReq.Method = "POST";
newReq.ContentType = "application/x-www-form-urlencoded";
var newRequestStr = incomingReqStr + "&cmd=_notify-validate";
newReq.ContentLength = newRequestStr.Length;
//write out the full parameters into the request
var streamOut = new StreamWriter(newReq.GetRequestStream(), System.Text.Encoding.ASCII);
streamOut.Write(newRequestStr);
streamOut.Close();
//Send request back to Paypal and receive response
var response = newReq.GetResponse();
return response;
}
19
Source : PaypalHelper.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public IPayPalPaymentDataTransferResponse GetPaymentDataTransferResponse(string idenreplacedyToken, string transactionId)
{
var query = string.Format("cmd=_notify-synch&tx={0}&at={1}", transactionId, idenreplacedyToken);
var request = (HttpWebRequest)WebRequest.Create(PayPalBaseUrl);
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = query.Length;
var streamOut = new StreamWriter(request.GetRequestStream(), Encoding.ASCII);
streamOut.Write(query);
streamOut.Close();
var streamIn = new StreamReader(request.GetResponse().GetResponseStream());
var response = streamIn.ReadToEnd();
streamIn.Close();
return new PayPalPaymentDataTransferResponse(response);
}
19
Source : ClientFactory.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static CookieContainer CreateCookieContainer(Uri uri, DateTime expires, byte[] data, int? timeout)
{
var request = CreateRequest(uri, timeout);
using (var reqStream = request.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
reqStream.Close();
using (var response = request.GetResponse() as HttpWebResponse)
{
if (response.StatusCode == HttpStatusCode.MovedPermanently)
{
var location = response.Headers["Location"];
if (!string.IsNullOrWhiteSpace(location))
{
var check = new Uri(location, UriKind.RelativeOrAbsolute);
var locationUrl = check.IsAbsoluteUri ? check : new Uri(uri, check);
return CreateCookieContainer(locationUrl, expires, data, timeout);
}
}
return CreateCookieContainer(expires, request.RequestUri, response.Cookies);
}
}
}
19
Source : RemotePost.cs
with MIT License
from Adoxio
with MIT License
from 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
Source : HttpHelper.cs
with GNU General Public License v3.0
from aduskin
with GNU General Public License v3.0
from aduskin
static HttpWebRequest Http_Core(string _type, string _url, Encoding _encoding, List<replacedem> _header, object _conmand = null)
{
#region 启动HTTP请求之前的初始化操作
bool isget = false;
if (_type == "GET")
{
isget = true;
}
if (isget)
{
if (_conmand is List<replacedem>)
{
List<replacedem> _conmand_ = (List<replacedem>)_conmand;
string param = "";
foreach (replacedem item in _conmand_)
{
if (string.IsNullOrEmpty(param))
{
if (_url.Contains("?"))
{
param += "&" + item.Name + "=" + item.Value;
}
else
{
param = "?" + item.Name + "=" + item.Value;
}
}
else
{
param += "&" + item.Name + "=" + item.Value;
}
}
_url += param;
}
}
Uri uri = null;
try
{
uri = new Uri(_url);
}
catch { }
#endregion
if (uri != null)
{
//string _scheme = uri.Scheme.ToUpper();
try
{
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uri);
req.Proxy = null;
req.Host = uri.Host;
req.Method = _type;
req.AllowAutoRedirect = false;
bool isContentType = true;
#region 设置请求头
if (_header != null && _header.Count > 0)
{
bool isnotHeader = true;
System.Collections.Specialized.NameValueCollection collection = null;
foreach (replacedem item in _header)
{
string _Lower_Name = item.Name.ToLower();
switch (_Lower_Name)
{
case "host":
req.Host = item.Value;
break;
case "accept":
req.Accept = item.Value;
break;
case "user-agent":
req.UserAgent = item.Value;
break;
case "referer":
req.Referer = item.Value;
break;
case "content-type":
isContentType = false;
req.ContentType = item.Value;
break;
case "cookie":
#region 设置COOKIE
string _cookie = item.Value;
CookieContainer cookie_container = new CookieContainer();
if (_cookie.IndexOf(";") >= 0)
{
string[] arrCookie = _cookie.Split(';');
//加载Cookie
//cookie_container.SetCookies(new Uri(url), cookie);
foreach (string sCookie in arrCookie)
{
if (string.IsNullOrEmpty(sCookie))
{
continue;
}
if (sCookie.IndexOf("expires") > 0)
{
continue;
}
cookie_container.SetCookies(uri, sCookie);
}
}
else
{
cookie_container.SetCookies(uri, _cookie);
}
req.CookieContainer = cookie_container;
#endregion
break;
default:
if (isnotHeader && collection == null)
{
var property = typeof(WebHeaderCollection).GetProperty("InnerCollection", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
if (property != null)
{
collection = property.GetValue(req.Headers, null) as System.Collections.Specialized.NameValueCollection;
}
isnotHeader = false;
}
//设置对象的Header数据
if (collection != null)
{
collection[item.Name] = item.Value;
}
break;
}
}
}
#endregion
#region 设置POST数据
if (!isget)
{
if (_conmand != null)
{
if (_conmand is List<replacedem>)
{
List<replacedem> _conmand_ = (List<replacedem>)_conmand;
//POST参数
if (isContentType)
{
req.ContentType = "application/x-www-form-urlencoded";
}
string param = "";
foreach (replacedem item in _conmand_)
{
if (string.IsNullOrEmpty(param))
{
param = item.Name + "=" + item.Value;
}
else
{
param += "&" + item.Name + "=" + item.Value;
}
}
byte[] bs = _encoding.GetBytes(param);
req.ContentLength = bs.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
reqStream.Close();
}
}
else if (_conmand is string[])
{
try
{
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
byte[] endbytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
req.ContentType = "multipart/form-data; boundary=" + boundary;
using (Stream reqStream = req.GetRequestStream())
{
string[] files = (string[])_conmand;
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
byte[] buff = new byte[1024];
for (int i = 0; i < files.Length; i++)
{
string file = files[i];
reqStream.Write(boundarybytes, 0, boundarybytes.Length);
string contentType = MimeMappingProvider.Shared.GetMimeMapping(file);
//string contentType = System.Web.MimeMapping.GetMimeMapping(file);
//string header = string.Format(headerTemplate, "file" + i, Path.GetFileName(file), contentType);
string header = string.Format(headerTemplate, "media", Path.GetFileName(file), contentType);//微信
byte[] headerbytes = _encoding.GetBytes(header);
reqStream.Write(headerbytes, 0, headerbytes.Length);
using (FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read))
{
int contentLen = fileStream.Read(buff, 0, buff.Length);
int Value = contentLen;
//文件上传开始
//tProgress.Invoke(new Action(() =>
//{
// tProgress.Maximum = (int)fileStream.Length;
// tProgress.Value = Value;
//}));
while (contentLen > 0)
{
//文件上传中
reqStream.Write(buff, 0, contentLen);
contentLen = fileStream.Read(buff, 0, buff.Length);
Value += contentLen;
//tProgress.Invoke(new Action(() =>
//{
// tProgress.Value = Value;
//}));
}
}
}
//文件上传结束
reqStream.Write(endbytes, 0, endbytes.Length);
}
}
catch
{
if (isContentType)
{
req.ContentType = null;
}
req.ContentLength = 0;
}
}
else
{
//POST参数
if (isContentType)
{
req.ContentType = "application/x-www-form-urlencoded";
}
string param = _conmand.ToString();
byte[] bs = _encoding.GetBytes(param);
req.ContentLength = bs.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
reqStream.Close();
}
}
}
else
{
req.ContentLength = 0;
}
}
#endregion
return req;
}
catch
{
}
}
return null;
}
19
Source : HttpURLConnectionClient.cs
with MIT License
from Adyen
with MIT License
from 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
Source : HttpURLConnectionClient.cs
with MIT License
from Adyen
with MIT License
from 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
Source : HttpURLConnectionClient.cs
with MIT License
from Adyen
with MIT License
from 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
Source : HttpApiCaller.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
public void CreateRequest()
{
var url = new StringBuilder();
url.Append($"{Host?.TrimEnd('/') + "/"}{ApiName?.TrimStart('/')}");
if (Query != null && Query.Count > 0)
{
bool first = true;
foreach (var kvp in Query)
{
if (string.IsNullOrEmpty(kvp.Key) || kvp.Value == null)
continue;
if (first)
{
first = false;
url.Append('?');
}
else
url.Append('&');
url.Append($"{kvp.Key}={HttpUtility.UrlEncode(kvp.Value, Encoding.UTF8)}");
}
}
RemoteUrl = url.ToString();
RemoteRequest = (HttpWebRequest)WebRequest.Create(RemoteUrl);
RemoteRequest.Headers.Add(HttpRequestHeader.Authorization, Authorization);
RemoteRequest.Timeout = ConfigurationManager.AppSettings.GetInt("httpTimeout", 30);
RemoteRequest.Method = Method;
RemoteRequest.KeepAlive = true;
if (Form != null && Form.Count > 0)
{
RemoteRequest.ContentType = "application/x-www-form-urlencoded";
var builder = new StringBuilder();
bool first = true;
foreach (var kvp in Form)
{
if (string.IsNullOrEmpty(kvp.Key) || kvp.Value == null)
continue;
if (first)
first = false;
else
url.Append('&');
builder.Append($"{kvp.Key}={HttpUtility.UrlEncode(kvp.Value, Encoding.UTF8)}");
}
using (var rs = RemoteRequest.GetRequestStream())
{
var formData = Encoding.UTF8.GetBytes(builder.ToString());
rs.Write(formData, 0, formData.Length);
}
}
else if (!string.IsNullOrWhiteSpace(Json))
{
RemoteRequest.ContentType = "application/json;charset=utf-8";
var buffer = Json.ToUtf8Bytes();
using (var rs = RemoteRequest.GetRequestStream())
{
rs.Write(buffer, 0, buffer.Length);
}
}
else
{
RemoteRequest.ContentType = "application/x-www-form-urlencoded";
}
}
19
Source : WebApiCaller.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
public ApiResult<TResult> Post<TResult>(string apiName, string form)
{
LogRecorderX.BeginStepMonitor("内部API调用" + ToUrl(apiName));
var ctx = string.IsNullOrEmpty(Bearer) ? null : $"Bearer {Bearer}";
LogRecorderX.MonitorTrace(ctx);
LogRecorderX.MonitorTrace("Arguments:" + form);
var req = (HttpWebRequest)WebRequest.Create(ToUrl(apiName));
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.Headers.Add(HttpRequestHeader.Authorization, ctx);
try
{
using (var rs = req.GetRequestStream())
{
var formData = Encoding.UTF8.GetBytes(form);
rs.Write(formData, 0, formData.Length);
}
}
catch (Exception ex)
{
LogRecorderX.Exception(ex);
LogRecorderX.EndStepMonitor();
return ApiResult.Error<TResult>(ErrorCode.RemoteError);
}
return GetResult<TResult>(req);
}
19
Source : WebApiCaller.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
public ApiValueResult Post(string apiName, string form)
{
LogRecorderX.BeginStepMonitor("内部API调用" + ToUrl(apiName));
var ctx = string.IsNullOrEmpty(Bearer) ? null : $"Bearer {Bearer}";
LogRecorderX.MonitorTrace(ctx);
LogRecorderX.MonitorTrace("Arguments:" + form);
var req = (HttpWebRequest)WebRequest.Create(ToUrl(apiName));
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.Headers.Add(HttpRequestHeader.Authorization, ctx);
try
{
using (var rs = req.GetRequestStream())
{
var formData = Encoding.UTF8.GetBytes(form);
rs.Write(formData, 0, formData.Length);
}
}
catch (Exception ex)
{
LogRecorderX.Exception(ex);
LogRecorderX.EndStepMonitor();
return ErrorResult(-3);
}
using (MonitorScope.CreateScope("Caller Remote"))
{
return GetResult(req);
}
}
19
Source : HttpApiCaller.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
public void CreateRequest(string apiName, string method, HttpRequest localRequest, RouteData data)
{
ApiName = apiName;
var url = new StringBuilder();
url.Append($"{Host?.TrimEnd('/') + "/"}{apiName?.TrimStart('/')}");
if (localRequest.QueryString.HasValue)
{
url.Append('?');
url.Append(data.Uri.Query);
}
RemoteUrl = url.ToString();
RemoteRequest = (HttpWebRequest) WebRequest.Create(RemoteUrl);
RemoteRequest.Headers.Add(HttpRequestHeader.Authorization, $"Bearer {data.Token}");
RemoteRequest.Timeout = RouteOption.Option.SystemConfig.HttpTimeOut;
RemoteRequest.Method = method;
RemoteRequest.KeepAlive = true;
if (localRequest.HasFormContentType)
{
RemoteRequest.ContentType = "application/x-www-form-urlencoded";
var builder = new StringBuilder();
builder.Append($"_api_context_={HttpUtility.UrlEncode(JsonConvert.SerializeObject(GlobalContext.Current), Encoding.UTF8)}");
foreach (var kvp in localRequest.Form)
{
builder.Append('&');
builder.Append($"{kvp.Key}=");
if (!string.IsNullOrEmpty(kvp.Value))
builder.Append($"{HttpUtility.UrlEncode(kvp.Value, Encoding.UTF8)}");
}
data.Form = builder.ToString();
using (var rs = RemoteRequest.GetRequestStream())
{
var formData = Encoding.UTF8.GetBytes(data.Form);
rs.Write(formData, 0, formData.Length);
}
}
else if (localRequest.ContentLength != null)
{
using (var texter = new StreamReader(localRequest.Body))
{
data.Context = texter.ReadToEnd();
texter.Close();
}
if (string.IsNullOrWhiteSpace(data.Context))
return;
RemoteRequest.ContentType = "application/json;charset=utf-8";
var buffer = data.Context.ToUtf8Bytes();
using (var rs = RemoteRequest.GetRequestStream())
{
rs.Write(buffer, 0, buffer.Length);
}
}
else
{
RemoteRequest.ContentType = localRequest.ContentType;
}
}
19
Source : HttpApiCaller.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
public void CreateRequest(string apiName, string method = "GET", string context = null)
{
ApiName = apiName;
var auth = Bearer;
_url = $"{Host?.TrimEnd('/') + "/"}{apiName?.TrimStart('/')}";
_webRequest = (HttpWebRequest)WebRequest.Create(_url);
_webRequest.Timeout = 30000;
_webRequest.KeepAlive = false;
_webRequest.Method = method;
if (!string.IsNullOrEmpty(context))
{
_webRequest.ContentType = "application/json";
_webRequest.Headers.Add(HttpRequestHeader.Authorization, auth);
using (var rs = _webRequest.GetRequestStream())
{
var formData = Encoding.UTF8.GetBytes(context);
rs.Write(formData, 0, formData.Length);
}
}
}
19
Source : MKMInteract.cs
with GNU Affero General Public License v3.0
from alexander-pick
with GNU Affero General Public License v3.0
from 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
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 : 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 : ServerSms.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from 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
Source : BitMaxProClient.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from 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
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 : 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 : 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 : 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 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 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 : HttpWebRequestFactory.cs
with MIT License
from aliyunmq
with MIT License
from aliyunmq
public Stream GetRequestContent()
{
return _request.GetRequestStream();
}
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 : 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 : 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 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 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 bool HTTPPost(string path, object data)
{
string str = JsonUtility.ToJson(data);
byte[] bytes = new System.Text.UTF8Encoding().GetBytes(str);
Debug.Log("Signaling: Posting HTTP data: " + str);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create($"{m_url}/{path}");
request.Method = "POST";
request.ContentType = "application/json";
request.Headers.Add("Session-Id", m_sessionId);
request.KeepAlive = false;
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(bytes, 0, bytes.Length);
dataStream.Close();
}
return (HTTPParseTextResponse(HTTPGetResponse(request)) != 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 : 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 : TranslatorModule.cs
with GNU Affero General Public License v3.0
from asmejkal
with GNU Affero General Public License v3.0
from asmejkal
[Command("translate", "Translates a piece of text.")]
[Alias("tr"), Alias("번역")]
[Parameter("From", LanguageRegex, ParameterType.String, "the language of the message")]
[Parameter("To", LanguageRegex, ParameterType.String, "the language to translate into")]
[Parameter("Message", ParameterType.String, ParameterFlags.Remainder, "the word or sentence you want to translate")]
[Comment("Korean = `ko` \nreplacedan = `ja` \nEnglish = `en` \nChinese(Simplified) = `zh-CH` \nChinese(Traditional) = `zh-TW` \nSpanish = `es` \nFrench = `fr` \nGerman = `de` \nRussian = `ru` \nPortuguese = `pt` \nItalian = `it` \nVietnamese = `vi` \nThai = `th` \nIndonesian = `id`")]
[Example("ko en 사랑해")]
public async Task Translate(ICommand command, ILogger logger)
{
await command.Message.Channel.TriggerTypingAsync();
var stringMessage = command["Message"].ToString();
var firstLang = command["From"].ToString();
var lastLang = command["To"].ToString();
var byteDataParams = Encoding.UTF8.GetBytes($"source={Uri.EscapeDataString(firstLang)}&target={Uri.EscapeDataString(lastLang)}&text={Uri.EscapeDataString(stringMessage)}");
try
{
var request = WebRequest.CreateHttp("https://openapi.naver.com/v1/papago/n2mt");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Headers.Add("X-Naver-Client-Id", _integrationOptions.Value.PapagoClientId);
request.Headers.Add("X-Naver-Client-Secret", _integrationOptions.Value.PapagoClientSecret);
request.ContentLength = byteDataParams.Length;
using (var st = request.GetRequestStream())
{
st.Write(byteDataParams, 0, byteDataParams.Length);
}
using (var responseClient = await request.GetResponseAsync())
using (var reader = new StreamReader(responseClient.GetResponseStream()))
{
var parserObject = JObject.Parse(await reader.ReadToEndAsync());
var trMessage = parserObject["message"]["result"]["translatedText"].ToString();
var translateSentence = trMessage.Truncate(EmbedBuilder.MaxDescriptionLength);
EmbedBuilder embedBuilder = new EmbedBuilder()
.Withreplacedle($"Translation from **{firstLang.ToUpper()}** to **{lastLang.ToUpper()}**")
.WithDescription(translateSentence)
.WithColor(new Color(0, 206, 56))
.WithFooter("Powered by Papago");
await command.Reply(embedBuilder.Build());
}
}
catch (WebException ex) when (ex.Response is HttpWebResponse r && r.StatusCode == HttpStatusCode.BadRequest)
{
throw new IncorrectParametersCommandException("Unsupported language combination.");
}
catch (WebException ex)
{
logger.LogError(ex, "Failed to reach Papago");
await command.Reply($"Couldn't reach Papago (error {(ex.Response as HttpWebResponse)?.StatusCode.ToString() ?? ex.Status.ToString()}). Please try again in a few seconds.");
}
}
See More Examples