public Stream Creat() { WebRequest inquiry = WebRequest.Create("http://api.lod-misis.ru/testassignment"); Answer = inquiry.GetResponse(); Stream stream = Answer.GetResponseStream(); return stream; }
/// <summary> /// /// </summary> /// <exception cref="System.ArgumentNullException">if response is null.</exception> /// <param name="response"></param> public WebResult(WebResponse response) { if (response == null) throw new ArgumentNullException(nameof(response)); this.Type = WebResultType.Succeed; this.Response = response; }
/// <summary> /// Initializes a new instance of the <see cref="WebResponseDetails"/> class. /// </summary> /// <param name="webResponse">The web response.</param> public WebResponseDetails(WebResponse webResponse) { if (webResponse == null) { throw new ArgumentNullException("webResponse", "Server response could not be null"); } // // Copy headers this.Headers = new Dictionary<string,string>(); if ((webResponse.Headers != null) && (webResponse.Headers.Count > 0)) { foreach (string key in webResponse.Headers.AllKeys) this.Headers.Add(key, webResponse.Headers[key]); } // // Copy body (raw) try { StreamReader reader = new StreamReader(webResponse.GetResponseStream(), System.Text.Encoding.Default); this.Body = reader.ReadToEnd(); } catch (ArgumentNullException exp_null) { // // No response stream ? System.Diagnostics.Trace.WriteLine("WebResponse does not have any response stream"); this.Body = string.Empty; } }
public Stream Get() { WebRequest request = WebRequest.Create("http://api.lod-misis.ru/testassignment"); response = request.GetResponse(); Stream stream = response.GetResponseStream(); return stream; }
/// <summary> /// 从Response获取错误信息 /// </summary> /// <param name="response"></param> /// <returns></returns> public static WfServiceInvokeException FromWebResponse(WebResponse response) { StringBuilder strB = new StringBuilder(); string content = string.Empty; using (Stream stream = response.GetResponseStream()) { StreamReader streamReader = new StreamReader(stream, Encoding.UTF8); content = streamReader.ReadToEnd(); } if (response is HttpWebResponse) { HttpWebResponse hwr = (HttpWebResponse)response; strB.AppendFormat("Status Code: {0}, Description: {1}\n", hwr.StatusCode, hwr.StatusDescription); } strB.AppendLine(content); WfServiceInvokeException result = new WfServiceInvokeException(strB.ToString()); if (response is HttpWebResponse) { HttpWebResponse hwr = (HttpWebResponse)response; result.StatusCode = hwr.StatusCode; result.StatusDescription = hwr.StatusDescription; } return result; }
/// <summary>Print the error message as it came from the server.</summary> private void PrintErrorResponse(WebResponse response) { if (response == null) { return; } Stream responseStream = response.GetResponseStream(); try { Stream errorStream = Console.OpenStandardError(); try { Copy(responseStream, errorStream); } finally { errorStream.Close(); } } finally { responseStream.Close(); } }
protected void initRequest() { request = null; response = null; jsonString = ""; uri = ""; }
public ICommandResponse ParseResponse(WebResponse response) { return new SetObjectACLResponse { Policy = response.Headers["x-emc-policy"] }; }
/// <summary> /// Process the web response and output corresponding objects. /// </summary> /// <param name="response"></param> internal override void ProcessResponse(WebResponse response) { if (null == response) { throw new ArgumentNullException("response"); } // check for Server Core, throws exception if -UseBasicParsing is not used if (ShouldWriteToPipeline && (!UseBasicParsing)) { VerifyInternetExplorerAvailable(true); } Stream responseStream = StreamHelper.GetResponseStream(response); if (ShouldWriteToPipeline) { // creating a MemoryStream wrapper to response stream here to support IsStopping. responseStream = new WebResponseContentMemoryStream(responseStream, StreamHelper.ChunkSize, this); WebResponseObject ro = WebResponseObjectFactory.GetResponseObject(response, responseStream, this.Context, UseBasicParsing); WriteObject(ro); // use the rawcontent stream from WebResponseObject for further // processing of the stream. This is need because WebResponse's // stream can be used only once. responseStream = ro.RawContentStream; responseStream.Seek(0, SeekOrigin.Begin); } if (ShouldSaveToOutFile) { StreamHelper.SaveStreamToFile(responseStream, QualifiedOutFile, this); } }
public static dynamic FromResponse(WebResponse response) { using (var stream = response.GetResponseStream()) { return FromStream(stream); } }
private void SetResponse(WebResponse response, Stream contentStream) { if (null == response) { throw new ArgumentNullException("response"); } BaseResponse = response; MemoryStream ms = contentStream as MemoryStream; if (null != ms) { _rawContentStream = ms; } else { Stream st = contentStream; if (contentStream == null) { st = StreamHelper.GetResponseStream(response); } long contentLength = response.ContentLength; if (0 >= contentLength) { contentLength = StreamHelper.DefaultReadBuffer; } int initialCapacity = (int)Math.Min(contentLength, StreamHelper.DefaultReadBuffer); _rawContentStream = new WebResponseContentMemoryStream(st, initialCapacity, null); } // set the position of the content stream to the beginning _rawContentStream.Position = 0; }
public virtual PageContent GetContent(WebResponse response) { using (MemoryStream memoryStream = GetRawData(response)) { String charset = GetCharsetFromHeaders(response); if (charset == null) { memoryStream.Seek(0, SeekOrigin.Begin); // Do not wrap in closing statement to prevent closing of this stream. StreamReader srr = new StreamReader(memoryStream, Encoding.ASCII); String body = srr.ReadToEnd(); charset = GetCharsetFromBody(body); } memoryStream.Seek(0, SeekOrigin.Begin); charset = CleanCharset(charset); Encoding e = GetEncoding(charset); string content = ""; using (StreamReader sr = new StreamReader(memoryStream, e)) { content = sr.ReadToEnd(); } PageContent pageContent = new PageContent(); pageContent.Bytes = memoryStream.ToArray(); pageContent.Charset = charset; pageContent.Encoding = e; pageContent.Text = content; return pageContent; } }
public void ProcessReponse(List<SearchResultItem> list, WebResponse resp) { var response = new StreamReader(resp.GetResponseStream()).ReadToEnd(); var info = JsonConvert.DeserializeObject<BergGetStockResponse>(response, new JsonSerializerSettings() { Culture = CultureInfo.GetCultureInfo("ru-RU") }); if (info != null && info.Resources.Length > 0) { foreach (var resource in info.Resources.Where(r => r.Offers != null)) { foreach (var offer in resource.Offers) { list.Add(new SearchResultItem() { Article = resource.Article, Name = resource.Name, Vendor = PartVendor.BERG, VendorPrice = offer.Price, Quantity = offer.Quantity, VendorId = resource.Id, Brand = resource.Brand.Name, Warehouse = offer.Warehouse.Name, DeliveryPeriod = offer.AveragePeriod, WarehouseId = offer.Warehouse.Id.ToString() }); } } } }
/// <summary> /// /// </summary> /// <param name="response"></param> /// <returns></returns> private static Encoding getEncoding(WebResponse response) { try { String contentType = response.ContentType; if (contentType == null) { return _encoding; } String[] strArray = contentType.ToLower(CultureInfo.InvariantCulture).Split(new char[] { ';', '=', ' ' }); Boolean isFind = false; foreach (String item in strArray) { if (item == "charset") { isFind = true; } else if (isFind) { return Encoding.GetEncoding(item); } } } catch (Exception exception) { if (((exception is ThreadAbortException) || (exception is StackOverflowException)) || (exception is OutOfMemoryException)) { throw; } } return _encoding; }
public override PageContent GetContent(WebResponse p_Response) { // Navigate to the requested page using the WebDriver. PhantomJS will navigate to the page // just like a normal browser and the resulting html will be set in the PageSource property. m_WebDriver.Navigate().GoToUrl(p_Response.ResponseUri); // Let the JavaScript execute for a while if needed, for instance if the pages are doing async calls. //Thread.Sleep(1000); // Try to retrieve the charset and encoding from the response or body. string pageBody = m_WebDriver.PageSource; string charset = GetCharsetFromHeaders(p_Response); if (charset == null) { charset = GetCharsetFromBody(pageBody); } Encoding encoding = GetEncoding(charset); PageContent pageContent = new PageContent { Encoding = encoding, Charset = charset, Text = pageBody, Bytes = encoding.GetBytes(pageBody) }; return pageContent; }
public PageContent GetContent(WebResponse response) { using (MemoryStream memoryStream = GetRawData(response)) { String charset = GetCharsetFromHeaders(response); if (charset == null) charset = GetCharsetFromBody(memoryStream); memoryStream.Seek(0, SeekOrigin.Begin); Encoding e = GetEncoding(charset); string content = ""; using (StreamReader sr = new StreamReader(memoryStream, e)) { content = sr.ReadToEnd(); } PageContent pageContent = new PageContent(); pageContent.Bytes = memoryStream.ToArray(); pageContent.Charset = charset; pageContent.Encoding = e; pageContent.Text = content; return pageContent; } }
public static bool SaveBinaryFile(WebResponse response, string FileName) { bool Value = true; byte[] buffer = new byte[1024]; try { if (File.Exists(FileName)) File.Delete(FileName); Stream outStream = File.Create(FileName); Stream inStream = response.GetResponseStream(); int l; do { l = inStream.Read(buffer, 0, buffer.Length); if (l > 0) outStream.Write(buffer, 0, l); } while (l > 0); outStream.Close(); inStream.Close(); } catch { Value = false; } return Value; }
private static IDictionary<RateLimitTypeEnum, RateLimit> GetRateLimits(WebResponse response) { var limits = new Dictionary<RateLimitTypeEnum, RateLimit>(); if (response.Headers == null) { return limits; } if (response.Headers.AllKeys.Contains("X-RateLimit-Max")) { int value; if (int.TryParse(response.Headers["X-RateLimit-Max"], out value)) { limits.Add(RateLimitTypeEnum.Max, new RateLimit { RateLimitType = RateLimitTypeEnum.Max, Value = value }); } } if (response.Headers.AllKeys.Contains("X-RateLimit-Current")) { int value; if (int.TryParse(response.Headers["X-RateLimit-Current"], out value)) { limits.Add(RateLimitTypeEnum.Current, new RateLimit { RateLimitType = RateLimitTypeEnum.Current, Value = value }); } } return limits; }
/// <summary> /// Initializes a new instance of the <see cref="AirbrakeResponse"/> class. /// </summary> /// <param name="response">The response.</param> /// <param name="content">The content.</param> public AirbrakeResponse(WebResponse response, string content) { this.log = LogManager.GetLogger(GetType()); this.content = content; this.errors = new AirbrakeResponseError[0]; if (response != null) { // TryGet is needed because the default behavior of WebResponse is to throw NotImplementedException // when a method isn't overridden by a deriving class, instead of declaring the method as abstract. this.contentLength = response.TryGet(x => x.ContentLength); this.contentType = response.TryGet(x => x.ContentType); this.headers = response.TryGet(x => x.Headers); this.isFromCache = response.TryGet(x => x.IsFromCache); this.isMutuallyAuthenticated = response.TryGet(x => x.IsMutuallyAuthenticated); this.responseUri = response.TryGet(x => x.ResponseUri); } try { Deserialize(content); } catch (Exception exception) { this.log.Fatal(f => f( "An error occurred while deserializing the following content:\n{0}", content), exception); } }
public ICommandResponse ParseResponse(WebResponse response) { var request = _computeRequestService.GenerateRequest(null, _apiKey); _authenticator.AuthenticateRequest(WebRequest.Create(""), _base64Secret);//((RestClient)_client).BuildUri((RestRequest)request), _base64Secret); return _client.Execute<MachineResponse>((RestRequest)request).Data; }
private static string ExtractJsonResponse(WebResponse response) { GetRateLimits(response); var responseStream = response.GetResponseStream(); if (responseStream == null) { throw new StackExchangeException("Response stream is empty, unable to continue"); } string json; using (var outStream = new MemoryStream()) { using (var zipStream = new GZipStream(responseStream, CompressionMode.Decompress)) { zipStream.CopyTo(outStream); outStream.Seek(0, SeekOrigin.Begin); using (var reader = new StreamReader(outStream, Encoding.UTF8)) { json = reader.ReadToEnd(); } } } return json; }
internal SharpBoxException(SharpBoxErrorCodes errorCode, Exception innerException, WebRequest request, WebResponse response) : base(GetErrorMessage(errorCode), innerException) { ErrorCode = errorCode; PostedRequet = request; DisposedReceivedResponse = response; }
public ExtendedHttpWebResponse(Uri responseUri, WebResponse response, Stream responseStream, CacheInfo cacheInfo) { this.responseUri = responseUri; this.response = response; this.responseStream = responseStream; this.cacheInfo = cacheInfo; }
public CouchbaseCluster(MemcacheClientConfiguration configuration, string bucket, IPEndPoint[] configurationHosts) { if (configurationHosts.Length == 0) throw new ArgumentException("There should be at least one value in the list", "configurationHosts"); _isInitialized = false; _linesStreamReader = null; _webResponse = null; _configuration = configuration; if (_configuration.Authenticator == null) _configuration.Authenticator = MemcacheClientConfiguration.SaslPlainAuthenticatorFactory(string.Empty, bucket, string.Empty); _bucket = bucket; _currentConfigurationHost = 0; _configurationHosts = configurationHosts; _memcacheNodes = new Dictionary<string, IMemcacheNode>(); _locator = null; _connectionTimer = new Timer(_ => ConnectToConfigurationStream(), null, Timeout.Infinite, Timeout.Infinite); _receivedInitialConfigurationBarrier = new ManualResetEventSlim(); }
public WebException(String msg, Exception inner, WebExceptionStatus status, WebResponse response) : base(msg, inner) { myresponse = response; mystatus = status; }
// Source: http://blogs.msdn.com/b/feroze_daud/archive/2004/03/30/104440.aspx public static String Decode(WebResponse response, Stream stream) { String charset = null; String contentType = response.Headers["content-type"]; if(contentType != null) { int index = contentType.IndexOf("charset="); if(index != -1) { charset = contentType.Substring(index + 8); } } MemoryStream data = new MemoryStream(); byte[] buffer = new byte[1024]; int read = stream.Read(buffer, 0, buffer.Length); while(read > 0) { data.Write(buffer, 0, read); read = stream.Read(buffer, 0, buffer.Length); } stream.Close(); Encoding encoding = Encoding.UTF8; try { if(charset != null) encoding = Encoding.GetEncoding(charset); } catch { } data.Seek(0, SeekOrigin.Begin); StreamReader streamReader = new StreamReader(data, encoding); return streamReader.ReadToEnd(); }
public void BeginStreaming() { try { request = new CampfireRequest(this.site) .CreateRequest(this.site.ApiUrlBuilder.Stream(this.room.ID), HttpMethod.GET); request.Timeout = -1; // yes, this is needed. regular authentication using the Credentials property does not work for streaming string token = string.Format("{0}:X", this.site.ApiToken); string encoding = Convert.ToBase64String(Encoding.UTF8.GetBytes(token)); request.Headers.Add("Authorization", "Basic " + encoding); response = request.GetResponse(); responseStream = response.GetResponseStream(); reader = new StreamReader(responseStream, Encoding.UTF8); del = new Action(() => { ReadNextMessage(reader); }); del.BeginInvoke(LineRead, null); } catch { Thread.Sleep(2500); BeginStreaming(); } }
private string ReadAll(WebResponse webResponse) { using (var reader = new StreamReader(webResponse.GetResponseStream())) { return reader.ReadToEnd(); } }
private DownloadData(WebResponse response, long size, long start) { this.response = response; this.size = size; this.start = start; this.stream = null; }
private Action<HttpWebRequest> HandleUnauthorizedResponse(RavenConnectionStringOptions options, WebResponse webResponse) { if (options.ApiKey == null) return null; var oauthSource = webResponse.Headers["OAuth-Source"]; var useBasicAuthenticator = string.IsNullOrEmpty(oauthSource) == false && oauthSource.EndsWith("/OAuth/API-Key", StringComparison.CurrentCultureIgnoreCase) == false; if (string.IsNullOrEmpty(oauthSource)) oauthSource = options.Url + "/OAuth/API-Key"; var authenticator = authenticators.GetOrAdd( GetCacheKey(options), _ => { if (useBasicAuthenticator) { return new BasicAuthenticator(enableBasicAuthenticationOverUnsecuredHttp: false); } return new SecuredAuthenticator(); }); return authenticator.DoOAuthRequest(oauthSource, options.ApiKey); }
//float lastCheckTime = 0f; public IEnumerator GetDownloadSizeOfBundlesA(List <AssetLoader.AssetBundleHash> assetBundlesToDownload, System.Action <long> result) { int size = 0; int count = assetBundlesToDownload.Count; //SceneLogIn.Instance.labelCheckAsset.text = "Calculate download size"; for (int i = 0; i < count; i++) { #if UNITY_ANDROID System.Net.WebRequest req = System.Net.HttpWebRequest.Create(url + "Android/" + assetBundlesToDownload[i].assetBundle); #endif #if UNITY_IOS System.Net.WebRequest req = System.Net.HttpWebRequest.Create(url + "iOS/" + assetBundlesToDownload[i].assetBundle); #endif req.Method = "HEAD"; req.Timeout = 10000; int ContentLength; using (System.Net.WebResponse resp = req.GetResponse()) { if (int.TryParse(resp.Headers.Get("Content-Length"), out ContentLength)) { size += ContentLength; //Debug.Log(assetBundlesToDownload[i].assetBundle + ", size: " + ContentLength); } resp.Close(); } req.Abort(); req = null; //System.GC.Collect(); //SceneLogIn.Instance.labelCheckAsset.text = "Calculate download size"; //if (Time.time > lastCheckTime + 1f) //{ // SceneLogIn.Instance.labelCheckAsset.text = "Calculate download size (" + i + "/" + count + ")"; // SceneLogIn.Instance.labelCheckAsset.Update(); // lastCheckTime = Time.time; // yield return new WaitForSeconds(0.1f); //} } result(size); //return size; yield break; }
public void CallingDoneOnANockReturnsTrueIfTheNockResponseWasUsed() { var nock1 = new nock("http://domain-name.com") .ContentType("application/json; encoding='utf-8'") .Get("/api/v2/action/") .Log(Console.WriteLine) .Reply(HttpStatusCode.OK, "The body"); var request = WebRequest.Create("http://domain-name.com/api/v2/action/") as HttpWebRequest; request.ContentType = "application/json; encoding='utf-8'"; request.Method = "GET"; System.Net.WebResponse response = request.GetResponse(); Assert.That(nock1.Done(), Is.True); }
/// <summary> /// Gets Filesize from the specified server endpoint /// </summary> /// <param name="url"></param> /// <returns>Filezise in bytes</returns> public static long ResponseSize(string url) { System.Net.WebRequest req = System.Net.HttpWebRequest.Create(url); req.Method = "HEAD"; long responseLength = 0; try { System.Net.WebResponse resp = req.GetResponse(); responseLength = resp.ContentLength; resp.Close(); }catch { } return(responseLength); }
/// <summary> /// Get the content size of a URL using the HEAD method /// </summary> /// <param name="strURL"></param> /// <returns></returns> public static long GetURLContentLength(string strURL) { try { HttpWebRequest wr = (HttpWebRequest)HttpWebRequest.Create(strURL); wr.Method = "HEAD"; wr.KeepAlive = false; System.Net.WebResponse wrp = wr.GetResponse(); wrp.Close(); return(wrp.ContentLength); } catch { return(-1); } }
private static bool isStatus(WebException e, HttpStatusCode code) { System.Net.WebResponse r = e.Response; if (r == null) { if (e.InnerException != null && e.InnerException is WebException) { return(isStatus(e.InnerException as WebException, code)); } } else if (r is HttpWebResponse && ((HttpWebResponse)r).StatusCode == code) { return(true); } return(false); }
public Lusi GetLusiResult(string inputMessage) { string strResult = ""; string uri = luis_Url + "&q=" + inputMessage; System.Net.WebRequest wrq = System.Net.WebRequest.Create(uri); wrq.Headers.Add("Ocp-Apim-Subscription-Key", luis_Key); wrq.Method = "GET"; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; //SSL3协议替换成TLS协议 System.Net.WebResponse wrp = wrq.GetResponse(); System.IO.StreamReader sr = new System.IO.StreamReader(wrp.GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8")); strResult = sr.ReadToEnd(); Lusi ro = JsonHelper.JsonDeserialize <Lusi>(strResult); return(ro); }
public void WhenANockHasBeenDefinedForTwoRequestsButOnlyOneRequestHasMadeCallingDoneWillReturnFalse() { var nock = new nock("http://domain-name.com") .ContentType("application/json; encoding='utf-8'") .Get("/api/v2/action/") .Reply(HttpStatusCode.OK, "The body") .Times(2); var request = WebRequest.Create("http://domain-name.com/api/v2/action/") as HttpWebRequest; request.ContentType = "application/json; encoding='utf-8'"; request.Method = "GET"; System.Net.WebResponse response = request.GetResponse(); Assert.That(nock.Done(), Is.False); }
static void Ex1() { Task.Run(async() => { string uri = "https://github.com/K38104011/DataStructureLearning"; System.Net.WebRequest req = System.Net.WebRequest.Create(uri); using (System.Net.WebResponse res = await req.GetResponseAsync()) using (System.IO.Stream stream = res.GetResponseStream()) using (System.IO.FileStream fs = System.IO.File.Create("code.html")) { stream?.CopyTo(fs); Console.WriteLine(res.ContentLength); } System.Diagnostics.Process.Start("code.html"); }); }
public static string HttpPost(string url, string postData, string contentType, string authorization, ref int statusCode) { try { System.Net.WebRequest req = System.Net.WebRequest.Create(url); //req.Proxy = new System.Net.WebProxy(ProxyString, true); //Add these, as we're doing a POST req.ContentType = contentType; req.Method = "POST"; //We need to count how many bytes we're sending. //Post'ed Faked Forms should be name=value& byte[] bytes = System.Text.Encoding.UTF8.GetBytes(postData); req.ContentLength = bytes.Length; if (!string.IsNullOrEmpty(authorization)) { req.Headers.Add("Authorization", authorization); } System.IO.Stream os = req.GetRequestStream(); os.Write(bytes, 0, bytes.Length); //Push it out there os.Close(); System.Net.WebResponse resp = req.GetResponse(); if (resp == null) { return(null); } System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()); var response = (HttpWebResponse)req.GetResponse(); statusCode = response.StatusCode.GetHashCode(); return(sr.ReadToEnd().Trim()); } catch (WebException ex) { statusCode = ((HttpWebResponse)ex.Response).StatusCode.GetHashCode(); throw ex; } catch (Exception ex) { throw ex; } }
//POSTでメッセージを送信する public static long SendPost(string message) { Stopwatch sw1 = Stopwatch.StartNew(); //有効なトークンを取得する //string token = CheckAccessToken.CheckToken(); //logger.Info("message:" + message); //バイト型配列に変換 byte[] postDataBytes = Encoding.UTF8.GetBytes(message); //WebRequestの作成 WebRequest req = WebRequest.Create(CallApiUrl); //メソッドにPOSTを指定 req.Method = "POST"; //ContentTypeを"application/x-www-form-urlencoded"にする req.ContentType = "application/json;charset=UTF-8"; //POST送信するデータの長さを指定 req.ContentLength = postDataBytes.Length; req.Headers.Add("X-Line-ChannelToken", Token); //データをPOST送信するためのStreamを取得 System.IO.Stream reqStream = req.GetRequestStream(); //送信するデータを書き込む reqStream.Write(postDataBytes, 0, postDataBytes.Length); reqStream.Close(); //サーバーからの応答を受信するためのWebResponseを取得 System.Net.WebResponse res = req.GetResponse(); //応答データを受信するためのStreamを取得 System.IO.Stream resStream = res.GetResponseStream(); //受信して表示 System.IO.StreamReader sr = new System.IO.StreamReader(resStream, Encoding.UTF8); string responseStr = sr.ReadToEnd(); sw1.Stop(); //logger.Info("SendPost response:time[" + sw1.ElapsedMilliseconds + "ms] Str[" + responseStr + "]"); //閉じる sr.Close(); return(sw1.ElapsedMilliseconds); }
private void LoadPicture(int i) { String url; try { url = json["hits"][i]["thumbnail_url"]; } catch { url = ""; Bitmap DefaultImage = Properties.Resources.NotFound; ImageList.Images.Add(DefaultImage); GatherProductInfo(i); return; } if (url == "") { Bitmap DefaultImage = Properties.Resources.NotFound; ImageList.Images.Add(DefaultImage); GatherProductInfo(i); return; } //load image from url System.Net.WebRequest request = System.Net.WebRequest.Create(url); try { System.Net.WebResponse resp = request.GetResponse(); System.IO.Stream respStream = resp.GetResponseStream(); Bitmap bmp = new Bitmap(respStream); respStream.Dispose(); ImageList.Images.Add(bmp); GatherProductInfo(i); } //catch bad url catch { Bitmap DefaultImage = Properties.Resources.NotFound; ImageList.Images.Add(DefaultImage); GatherProductInfo(i); return; } }
public static string HTTP_POST(string Url, string Data) { string Out = String.Empty; System.Net.WebRequest req = System.Net.WebRequest.Create(Url); try { req.Method = "POST"; req.Timeout = 100000; req.ContentType = "application/x-www-form-urlencoded"; byte[] sentData = Encoding.UTF8.GetBytes(Data); req.ContentLength = sentData.Length; using (System.IO.Stream sendStream = req.GetRequestStream()) { sendStream.Write(sentData, 0, sentData.Length); sendStream.Close(); } System.Net.WebResponse res = req.GetResponse(); System.IO.Stream ReceiveStream = res.GetResponseStream(); using (System.IO.StreamReader sr = new System.IO.StreamReader(ReceiveStream, Encoding.UTF8)) { Char[] read = new Char[256]; int count = sr.Read(read, 0, 256); while (count > 0) { String str = new String(read, 0, count); Out += str; count = sr.Read(read, 0, 256); } } } catch (ArgumentException ex) { Out = string.Format("HTTP_ERROR :: The second HttpWebRequest object has raised an Argument Exception as 'Connection' Property is set to 'Close' :: {0}", ex.Message); } catch (WebException ex) { Out = string.Format("HTTP_ERROR :: WebException raised! :: {0}", ex.Message); } catch (Exception ex) { Out = string.Format("HTTP_ERROR :: Exception raised! :: {0}", ex.Message); } return(Out); }
/// <summary> /// подгружаются данные физического лица /// </summary> /// <param name="id">Id сотрудника - нужно для совместимости с подгружаемыми скриптами приложения "Пользователи"</param> public ActionResult UserProxy(int id) { System.Net.HttpWebRequest rq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(Configuration.AppSettings.URI_user_form_simple + "?id=" + id); if (rq.CookieContainer == null) { rq.CookieContainer = new CookieContainer(); } rq.CookieContainer.Add(new Cookie("tz", UserContext.ClientTimeZoneOffset.ToString(), "/", Configuration.AppSettings.Domain)); rq.Method = "GET"; var authHeader = HttpContext.Request.Headers["Authorization"]; if (authHeader != null && authHeader.StartsWith("Basic")) { //var encodedUsernamePassword = authHeader.Substring("Basic ".Length).Trim(); //var encoding = System.Text.Encoding.GetEncoding("iso-8859-1"); //string usernamePassword = encoding.GetString(Convert.FromBase64String(encodedUsernamePassword)); //String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password)); rq.Headers.Add("Authorization", authHeader); } else { rq.Credentials = System.Net.CredentialCache.DefaultCredentials; } System.Net.WebResponse rs = rq.GetResponse(); System.IO.Stream stream = rs.GetResponseStream(); StreamReader readStream = new StreamReader(stream, System.Text.Encoding.UTF8); string s = readStream.ReadToEnd(); // подмена относительных ссылок на абсолютные в приложении "USERS" //Regex r = new Regex("([^0-9a-zа-я\\/:-_.])([0-9a-zа-я\\/:-_.]{1,}.aspx)", RegexOptions.IgnoreCase | RegexOptions.Multiline); //s = r.Replace(s, new MatchEvaluator(replaceURL)); // s += @" //<script language='javascript'> // function iframe_window_resize() // { // parent.document.all('ifrUser').style.height=document.body.scrollHeight + 5 + 'px'; // } // window.attachEvent('onresize',iframe_window_resize); // window.attachEvent('onload',iframe_window_resize); // window.document.attachEvent('onclick',iframe_window_resize); // window.document.attachEvent('onkeypress',iframe_window_resize); //</script>"; return(Content(s)); }
/// <summary> /// Starts the download. /// </summary> public IEnumerator StartDownload() { if (!downloadInProgress) { string totalSize = ""; System.Net.WebRequest req = System.Net.HttpWebRequest.Create(HTTPGameFileLocation + "upload_" + currentVer + ".thln"); req.Method = "HEAD"; using (System.Net.WebResponse resp = req.GetResponse()) { long ContentLength; if (long.TryParse(resp.Headers.Get("Content-Length"), out ContentLength)) { totalSize = GetBytesReadable(ContentLength); } } DownloadStatus = LocalizationManager.LangStrings[5]; LogGenerator.GenerateDownloadLog("Download started: " + HTTPGameFileLocation + "upload_" + currentVer + ".thln"); CompFileToDownload = new WWW(HTTPGameFileLocation + "upload_" + currentVer + ".thln"); while (!CompFileToDownload.isDone) { downloadInProgress = true; progressFill.fillAmount = CompFileToDownload.progress; DownloadProgress = (CompFileToDownload.progress * 100).ToString("F2") + "%/100% --- " + totalSize; yield return(null); } DownloadProgress = (CompFileToDownload.progress * 100).ToString("F2") + "%/100% --- " + totalSize; progressFill.fillAmount = CompFileToDownload.progress; if (!string.IsNullOrEmpty(CompFileToDownload.error)) { Debug.Log(CompFileToDownload.text + CompFileToDownload.error); } else { string pth = Application.dataPath; #if UNITY_EDITOR pth += "/.."; #endif downloadInProgress = false; LogGenerator.GenerateDownloadLog("Download done."); Debug.Log("done"); File.WriteAllBytes(pth + "/upload_" + currentVer + ".thln", CompFileToDownload.bytes); downloadInProgress = true; progressFill.fillAmount = 0; StaticCoroutine.Start(Decompressor.DecompressToDirectory(pth + "/upload_" + currentVer + ".thln", pth + "/" + GameName + "/")); } } }
private void loginSc6() { System.Net.WebRequest req = System.Net.WebRequest.Create(baseUrl + "/Login"); System.Net.WebResponse resp = req.GetResponse(); System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()); String respStr = sr.ReadToEnd().Trim(); updateViewstate(respStr); // Earlier Versions of SC6 if (respStr.Contains("ctl00$Main$ctl03")) { sc6loginbuttonid = "ctl00$Main$ctl03"; } // Later Versions of SC6 if (respStr.Contains("ctl00$Main$ctl05")) { sc6loginbuttonid = "ctl00$Main$ctl05"; } // ScreenConnect 20 if (respStr.Contains("ctl00$Main$loginButton")) { sc6loginbuttonid = "ctl00$Main$loginButton"; } String loginString = ""; loginString += "__EVENTARGUMENT=&"; loginString += "__EVENTTARGET=&"; loginString += "__LASTFOCUS=&"; loginString += "__VIEWSTATE=" + HttpUtility.UrlEncode(aspViewState) + "&"; loginString += "__VIEWSTATEGENERATOR=" + HttpUtility.UrlEncode(aspEventValidation) + "&"; loginString += HttpUtility.UrlEncode(sc6loginbuttonid) + "=" + HttpUtility.UrlEncode("Login") + "&"; loginString += HttpUtility.UrlEncode("ctl00$Main$passwordBox") + "=" + HttpUtility.UrlEncode(nc.Password) + "&"; loginString += HttpUtility.UrlEncode("ctl00$Main$userNameBox") + "=" + HttpUtility.UrlEncode(nc.UserName); try { updateViewstate(HttpPost(baseUrl + "/Login", loginString, true)); } catch (TimeoutException) { // Retry Login - sometimes takes too long? updateViewstate(HttpPost(baseUrl + "/Login", loginString, true)); } }
/// <summary> /// Отправить запрос и получить ответ /// </summary> /// <param name="url"></param> /// <param name="api_comand"></param> /// <param name="metod"></param> /// <param name="accept"></param> /// <returns></returns> public string Select(string url, string api_comand, string metod, string accept) { try { //String.Format("Выполняем запрос к WebAPI, url:{0}, api_comand {1}, metod {2}, accept {3}", url, api_comand, metod, accept).WriteInformation(eventID); ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3; HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url + api_comand); request.Method = metod; request.PreAuthenticate = true; request.Credentials = CredentialCache.DefaultCredentials; request.Accept = accept; try { using (System.Net.WebResponse response = request.GetResponse()) { try { using (System.IO.StreamReader rd = new System.IO.StreamReader(response.GetResponseStream())) { return(rd.ReadToEnd()); } } catch (Exception e) { e.ExceptionLog(String.Format("Ошибка создания StreamReader ответа, команда {0}, метод {1}, accept {2}", api_comand, metod, accept), this.eventID); return(null); } } } catch (Exception e) { e.ExceptionLog(String.Format("Ошибка получения ответа WebResponse, команда {0}, метод {1}, accept {2}", api_comand, metod, accept), this.eventID); return(null); } } catch (Exception e) { e.ExceptionMethodLog(String.Format("Select(url={0},api_comand={1},metod={2},accept={3})", url, api_comand, metod, accept), this.eventID); return(null); } }
public static string GetResponse_POST(string url, Dictionary <string, string> parameters) { try { //Concatenamos los parametros, OJO: NO se añade el caracter "?" string parametrosConcatenados = ConcatParams(parameters); System.Net.WebRequest wr = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); wr.Method = "POST"; wr.ContentType = "application/x-www-form-urlencoded"; System.IO.Stream newStream; //Codificación del mensaje System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); byte[] byte1 = encoding.GetBytes(parametrosConcatenados); wr.ContentLength = byte1.Length; //Envio de parametros newStream = wr.GetRequestStream(); newStream.Write(byte1, 0, byte1.Length); // Obtiene la respuesta System.Net.WebResponse response = wr.GetResponse(); // Stream con el contenido recibido del servidor newStream = response.GetResponseStream(); System.IO.StreamReader reader = new System.IO.StreamReader(newStream); // Leemos el contenido string responseFromServer = reader.ReadToEnd(); // Cerramos los streams reader.Close(); newStream.Close(); response.Close(); return(responseFromServer); } catch (System.Web.HttpException ex) { if (ex.ErrorCode == 404) { throw new Exception("Not found remote service " + url); } else { throw ex; } } }
/// <summary> /// POST请求(https未做验证考虑) /// </summary> /// <param name="url">请求URL</param> /// <param name="param">参数列表(如果在url中已经追加参数则此值可为null或空字符)</param> /// <returns></returns> public static TResult WebPostRequest <TResult>(string url, Dictionary <string, string> param, bool isJson = false, Dictionary <string, string> headers = null) where TResult : class { System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); //webRequest.KeepAlive = true; //webRequest.AllowAutoRedirect = true; webRequest.Method = "POST"; string paramStr = string.Empty; if (isJson) { webRequest.ContentType = "application/json"; paramStr = param.ElementAt(0).Value; } else { webRequest.ContentType = "application/x-www-form-urlencoded"; for (int i = 0; i < param.Count; i++) { paramStr += param.ElementAt(i).Key + "=" + param.ElementAt(i).Value + "&"; } paramStr = paramStr.Substring(0, paramStr.LastIndexOf("&")); } if (headers != null) { foreach (var item in headers) { webRequest.Headers.Add(item.Key, item.Value); } } //将URL编码后的字符串转化为字节 byte[] byteArray = Encoding.UTF8.GetBytes(paramStr); //设置请求的 ContentLength webRequest.ContentLength = byteArray.Length; //获得请 求流 System.IO.Stream dataStream = webRequest.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); // 关闭请求流 dataStream.Close(); // 获得响应流 System.Net.WebResponse response = webRequest.GetResponse(); dataStream = response.GetResponseStream(); System.IO.StreamReader reader = new System.IO.StreamReader(dataStream); //string cookie = response.Headers.Get("Set-Cookie"); string str = reader.ReadToEnd(); return(JsonConvert.DeserializeObject <TResult>(str)); }
private String GetGateway() { string url = "http://checkip.dyndns.org"; System.Net.WebRequest req = System.Net.WebRequest.Create(url); System.Net.WebResponse resp = req.GetResponse(); System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()); string response = sr.ReadToEnd().Trim(); string[] AllData = response.Split(':'); string dataString = AllData[1].Substring(1); string[] data = dataString.Split('<'); string ip = data[0]; return(ip); }
public Bitmap getbitmap(String s) { Bitmap b = null; try { System.Net.WebRequest request = System.Net.WebRequest.Create(s); System.Net.WebResponse response = request.GetResponse(); System.IO.Stream responseStream = response.GetResponseStream(); b = new Bitmap(responseStream); // b.SetResolution(b.Width, ds.Height); } catch { } return(b); }
public string GetResponstByUrlString(string urlStr) { var type = "utf-8"; System.Net.WebRequest wReq = System.Net.WebRequest.Create(urlStr); System.Net.WebResponse wResp = wReq.GetResponse(); System.IO.Stream respStream = wResp.GetResponseStream(); string data = ""; using (System.IO.StreamReader reader = new System.IO.StreamReader(respStream, Encoding.GetEncoding(type))) { data = reader.ReadToEnd(); } data = Regex.Unescape(data); return(data); }
public void NockedResponseCorrectlyRespondsBasedOnFunctionHeaderFiltersIfFunctionReturnsTrue() { var nock = new nock("http://domain-name.com") .ContentType("application/json; encoding='utf-8'") .MatchHeaders((headers) => { return(headers["fish"] == "chips"); }) .Get("/api/v2/action/") .Reply(HttpStatusCode.OK, "The body"); var request = WebRequest.Create("http://domain-name.com/api/v2/action/") as HttpWebRequest; request.ContentType = "application/json; encoding='utf-8'"; request.Headers.Add("fish", "chips"); request.Method = "GET"; System.Net.WebResponse response = request.GetResponse(); Assert.That(nock.Done(), Is.True); }
public static string Send_Sms(string text, string phone, string emza, string smsNumber, double warning) { PARSGREEN.API.SMS.Profile.ProfileService p = new PARSGREEN.API.SMS.Profile.ProfileService(); double creidet = p.GetCredit(emza); if (creidet == -64) // chek kardane dorost boodane emza digital { MessageBox.Show("امضا دیجیتال اشتباه است", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Error); return("-64"); } string pattern = "http://login.parsgreen.com/UrlService/sendSMS.ashx?from=" + smsNumber + "&to=" + phone + "&text=" + text + "&signature=" + emza; //MessageBox.Show(pattern); System.IO.Stream st = null; System.IO.StreamReader sr = null; HttpWebRequest req = (HttpWebRequest)WebRequest.Create(pattern); Encoding encode = System.Text.Encoding.UTF8; //MessageBox.Show(message2.Length.ToString()); System.Net.WebResponse resp = req.GetResponse(); st = resp.GetResponseStream(); sr = new System.IO.StreamReader(st, Encoding.UTF8); string result = sr.ReadToEnd().Substring(12, 1); //MessageBox.Show(sr.ReadToEnd()); //Get_Return_Message_Sms(int.Parse(result); //lblError.Text = Get_Return_Message_Sms(int.Parse(result)); sr.Close(); resp.Close(); //--------- if (creidet < warning) { MessageBox.Show("اعتبار پنل پیامک کمتر از" + warning + " ریال است", "پنل پیامک", MessageBoxButtons.OK, MessageBoxIcon.Warning); } //------- if (result == "0") { MessageBox.Show(text, "پیام ارسال شده"); return("0"); } return(result); }
public static string GetMethod(string url) { try { WebRequest.DefaultWebProxy = WebRequest.GetSystemWebProxy(); System.Net.WebRequest wrq = System.Net.WebRequest.Create(url); wrq.Method = "GET"; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; System.Net.WebResponse wrp = wrq.GetResponse(); System.IO.StreamReader sr = new System.IO.StreamReader(wrp.GetResponseStream(), System.Text.Encoding.GetEncoding("UTF-8")); return(sr.ReadToEnd()); } catch (Exception ex) { return(ex.Message); } }
public static Image GetImage(string imgUrl) { Image image = null; try { WebRequest webreq = WebRequest.Create(imgUrl); System.Net.WebResponse webres = webreq.GetResponse(); Stream stream = webres.GetResponseStream(); image = Image.FromStream(stream); stream.Close(); } catch (Exception) { } return(image); }
public static Image favicon(String u) //site faviconu çek { var url = new Uri(u); try { var iconURL = "http://www.google.com/s2/favicons?domain=" + url.Host; System.Net.WebRequest request = System.Net.HttpWebRequest.Create(iconURL); System.Net.WebResponse response = request.GetResponse(); System.IO.Stream stream = response.GetResponseStream(); return(Image.FromStream(stream)); } catch { return(null); } }
public static string GetRealIPAddress() { string url = "http://checkip.dyndns.org"; System.Net.WebRequest req = System.Net.WebRequest.Create(url); System.Net.WebResponse resp = req.GetResponse(); System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()); string response = sr.ReadToEnd().Trim(); string[] a = response.Split(':'); string a2 = a[1].Substring(1); string[] a3 = a2.Split('<'); string a4 = a3[0]; return(a4); }
/// <summary> /// 抓取网页源码 /// </summary> /// <param name="url"></param> /// <param name="Encoding"></param> /// <returns></returns> private string GetSourceTextByUrl(string url, string Encoding) { try { System.Net.WebRequest request = System.Net.WebRequest.Create(url); request.Timeout = 20000; System.Net.WebResponse response = request.GetResponse(); System.IO.Stream resStream = response.GetResponseStream(); System.IO.StreamReader sr = new System.IO.StreamReader(resStream, System.Text.Encoding.GetEncoding(Encoding)); return(sr.ReadToEnd()); } catch { return(""); } }
/// <summary> /// Get content length /// </summary> /// <returns>return length in bytes or -1 (failed)</returns> public static long GetContentLength() { System.Net.WebRequest req = System.Net.HttpWebRequest.Create(ClamWinExe); SetProxy(ref req); req.Method = "HEAD"; System.Net.WebResponse resp = req.GetResponse(); long ContentLength; if (long.TryParse(resp.Headers.Get("Content-Length"), out ContentLength)) { return(ContentLength); } else { return(-1); } }
void getAssetBundleSize(string bundleName) { WebRequest req = HttpWebRequest.Create(string.Format(_path, bundleName)); req.Method = "HEAD"; float ContentLength; using (System.Net.WebResponse resp = req.GetResponse()) { // float.TryParse(resp.ContentLength.ToString(), out ContentLength); len = resp.ContentLength.ToString(); } // len = len.Substring(0, 3); totalLen = int.Parse(len); }