public GetResponse( WebRequest request ) : base(request) { SortedList metadata = extractMetadata( response ); string body = Utils.slurpInputStream( response.GetResponseStream() ); this.obj = new S3Object( body, metadata ); }
public HttpJsonRequest(string url, string method, JObject metadata) { webRequest = WebRequest.Create(url); WriteMetadata(metadata); webRequest.Method = method; webRequest.ContentType = "application/json"; }
public RequestState() { _bufferRead = new byte[_bufferSize]; _requestData = new StringBuilder(String.Empty); _request = null; _responseStream = null; }
public void SignRequestLite(WebRequest webRequest) { if (webRequest == null) throw new ArgumentNullException("webRequest"); webRequest.Headers[this.headerName] = this.headerValue(); }
public Authorization Authenticate (string challenge, WebRequest webRequest, ICredentials credentials) { if (authObject == null) return null; return authObject.Authenticate (challenge, webRequest, credentials); }
public static string SendHttpPost(WebRequest request, YahooMessengerAuthentication authentication, string content) { request.Method = "POST"; byte[] byteArray = Encoding.UTF8.GetBytes(content); request.ContentLength = byteArray.Length; var dataStream = request.GetRequestStream(); // Write the data to the request stream. dataStream.Write(byteArray, 0, byteArray.Length); // Close the Stream object. dataStream.Close(); using(var response = (HttpWebResponse) request.GetResponse()) { if (response == null) throw new NullReferenceException(); var respCode = response.StatusCode; if (respCode != HttpStatusCode.OK) throw new HttpException(HttpException.HTTP_OK_NOT_RECEIVED, respCode.ToString()); dataStream = response.GetResponseStream(); if (dataStream == null) throw new NullReferenceException(); var reader = new StreamReader(dataStream); var responseFromServer = new StringBuilder(""); responseFromServer.Append(reader.ReadToEnd()); reader.Close(); dataStream.Close(); response.Close(); return responseFromServer.ToString(); } }
public void StartAsync(HttpContext context, string url) { this.m_context = context; this.m_request = HttpWebRequest.Create(url); this.m_request.BeginGetResponse(this.EndGetResponseCallback, null); }
// Overrides WebClien'ts GetWebResponse to add response cookies to the cookie container protected override WebResponse GetWebResponse(WebRequest request, IAsyncResult result) { WebResponse response = base.GetWebResponse(request, result); ReadCookies(response); responseURL = response.ResponseUri; return response; }
public RequestState(WebRequest request) { BufferRead = new byte[BUFFER_SIZE]; RequestData = new StringBuilder(String.Empty); Request = request; ResponseStream = null; }
public void UpdateHeaders(WebRequest webRequest) { if (operationsHeadersDictionary != null) { foreach (var kvp in operationsHeadersDictionary) { webRequest.Headers[kvp.Key] = kvp.Value; } } if(operationsHeadersColletion != null) { foreach (string header in operationsHeadersColletion) { try { webRequest.Headers[header] = operationsHeadersColletion[header]; } catch (Exception e) { throw new InvalidOperationException( "Failed to set header '" + header + "' to the value: " + operationsHeadersColletion[header], e); } } } }
public MyWebRequest(string url, string proxyServer) { // Create a request using a URL that can receive a post. request = WebRequest.Create(url); request.Proxy = new WebProxy(proxyServer); }
private static string ExecuteWebRequest(WebRequest webRequest) { try { using (var response = webRequest.GetResponse()) { return ReadStream(response.GetResponseStream()); } } catch (WebException webException) { if (webException.Response != null) { var statusCode = ((HttpWebResponse)webException.Response).StatusCode; var romitError = new RomitError(); if (webRequest.RequestUri.ToString().Contains("oauth")) romitError = Mapper<RomitError>.MapFromJson(ReadStream(webException.Response.GetResponseStream())); else romitError = Mapper<RomitError>.MapFromJson(ReadStream(webException.Response.GetResponseStream()), "error"); throw new RomitException(statusCode, romitError, romitError.Message); } throw; } }
public RequestState() { bufferRead = new byte[BUFFER_SIZE]; //requestData = new StringBuilder(); request = null; streamResponse = null; }
private static void CopyHttpRequestProps (WebRequest source, WebRequest copy) { var httpSource = source as HttpWebRequest; if (httpSource == null) return; var httpCopy = (HttpWebRequest)copy; //httpCopy.Accept = httpSource.Accept; //httpCopy.Connection = httpSource.Connection; //httpCopy.ContentLength = httpSource.ContentLength; //httpCopy.Date = httpSource.Date; //httpCopy.Expect = httpSource.Expect; //httpCopy.Host = httpSource.Host; //httpCopy.IfModifiedSince = httpSource.IfModifiedSince; //httpCopy.Referer = httpSource.Referer; //httpCopy.TransferEncoding = httpSource.TransferEncoding; //httpCopy.UserAgent = httpSource.UserAgent; httpCopy.AllowAutoRedirect = httpSource.AllowAutoRedirect; httpCopy.AllowReadStreamBuffering = httpSource.AllowReadStreamBuffering; httpCopy.AllowWriteStreamBuffering = httpSource.AllowWriteStreamBuffering; httpCopy.AutomaticDecompression = httpSource.AutomaticDecompression; httpCopy.ClientCertificates = httpSource.ClientCertificates; httpCopy.ContinueTimeout = httpSource.ContinueTimeout; httpCopy.CookieContainer = httpSource.CookieContainer; httpCopy.KeepAlive = httpSource.KeepAlive; httpCopy.MaximumAutomaticRedirections = httpSource.MaximumAutomaticRedirections; httpCopy.MaximumResponseHeadersLength = httpSource.MaximumResponseHeadersLength; httpCopy.MediaType = httpSource.MediaType; httpCopy.Pipelined = httpSource.Pipelined; httpCopy.ProtocolVersion = httpSource.ProtocolVersion; httpCopy.ReadWriteTimeout = httpSource.ReadWriteTimeout; httpCopy.SendChunked = httpSource.SendChunked; httpCopy.ServerCertificateValidationCallback = httpSource.ServerCertificateValidationCallback; httpCopy.UnsafeAuthenticatedConnectionSharing = httpSource.UnsafeAuthenticatedConnectionSharing; }
public void ScanSite(string url, string postData) { request = CreateRequest(url); state = new RequestState(request); MethodPost(url, postData); }
internal bool Invoke(string hostName, ServicePoint servicePoint, X509Certificate certificate, WebRequest request, X509Chain chain, SslPolicyErrors sslPolicyErrors) { PolicyWrapper policyWrapper = new PolicyWrapper(m_CertificatePolicy, servicePoint, (WebRequest) request); if (m_Context == null) { return policyWrapper.CheckErrors(hostName, certificate, chain, sslPolicyErrors); } else { ExecutionContext execContext = m_Context.CreateCopy(); CallbackContext callbackContext = new CallbackContext(policyWrapper, hostName, certificate, chain, sslPolicyErrors); ExecutionContext.Run(execContext, Callback, callbackContext); return callbackContext.result; } }
/// <summary> /// Authorizes the specified context. /// </summary> /// <param name="context">The context.</param> protected override void AuthenticateCore(WebRequest context) { context = Enforce.NotNull(context, () => context); // Authorize the request. context.Credentials = this.Credentials; }
static WebResponse InitiateRequest(WebRequest request) { var response = request.GetResponse(); var status = ((HttpWebResponse)response).StatusCode; if (Convert.ToInt32(status) >= 400) throw new Exception("Error making request"); return response; }
public ListAllMyBucketsResponse( WebRequest request ) : base(request) { buckets = new ArrayList(); string rawBucketXML = Utils.slurpInputStreamAsString( response.GetResponseStream() ); XmlDocument doc = new XmlDocument(); doc.LoadXml( rawBucketXML ); foreach (XmlNode node in doc.ChildNodes) { if (node.Name.Equals("ListAllMyBucketsResult")) { foreach (XmlNode child in node.ChildNodes) { if (child.Name.Equals("Owner")) { owner = new Owner(child); } else if (child.Name.Equals("Buckets")) { foreach (XmlNode bucket in child.ChildNodes) { if (bucket.Name.Equals("Bucket")) { buckets.Add(new Bucket(bucket)); } } } } } } }
//--------------------------------------------------- // @Name: attemptConnection // @Author: Lane - PeePeeSpeed // @Inputs: string url, string queue // @Outputs: NULL // // @Desc: Attempts to create a connection // to the server for data transfer. //--------------------------------------------------- public void attemptConnection(string u, string q) { try { wrGetUrl = WebRequest.Create(u + "?cmd=get&Value=" + q); objStream = wrGetUrl.GetResponse().GetResponseStream(); objReader = new StreamReader(objStream); //assert here? } catch (System.Net.WebException) { DialogResult dialogResult = MessageBox.Show("Could not establish connection to server\n\nDo you want to try again? System will exit on No.", "Error", MessageBoxButtons.YesNo); switch (dialogResult) { case DialogResult.Yes: attemptConnection(u, q); break; case DialogResult.No: System.Environment.Exit(0); break; } } }
static Authorization InternalAuthenticate (WebRequest webRequest, ICredentials credentials) { HttpWebRequest request = webRequest as HttpWebRequest; if (request == null || credentials == null) return null; NetworkCredential cred = credentials.GetCredential (request.AuthUri, "basic"); if (cred == null) return null; string userName = cred.UserName; if (userName == null || userName == "") return null; string password = cred.Password; string domain = cred.Domain; byte [] bytes; // If domain is set, MS sends "domain\user:password". if (domain == null || domain == "" || domain.Trim () == "") bytes = GetBytes (userName + ":" + password); else bytes = GetBytes (domain + "\\" + userName + ":" + password); string auth = "Basic " + Convert.ToBase64String (bytes); return new Authorization (auth); }
// ICertificatePolicy public bool CheckValidationResult(ServicePoint sp, X509Certificate cert, WebRequest request, int problem) { if (problem == 0) { // Check whether we have accumulated any problems so far: ArrayList problemArray = (ArrayList) request2problems_[request]; if (problemArray == null) { // No problems so far return true; } string problemList = ""; foreach (uint problemCode in problemArray) { string problemText = (string) problem2text_[problemCode]; if (problemText == null) { problemText = "Unknown problem"; } problemList += "* " + problemText + "\n\n"; } request2problems_.Remove(request); System.Console.WriteLine("There were one or more problems with the server certificate:\n\n" + problemList); return true; } else { // Stash the problem in the problem array: ArrayList problemArray = (ArrayList) request2problems_[request]; if (problemArray == null) { problemArray = new ArrayList(); request2problems_[request] = problemArray; } problemArray.Add((uint) problem); return true; } }
public RequestState() { bufferRead = new byte[BUFFER_SIZE]; requestData = new StringBuilder(""); request = null; responseStream = null; }
public static string SendHttpGet(WebRequest request, YahooMessengerAuthentication authentication) { request.Method = "GET"; if(authentication!=null) { if(!authentication.IsUsingOAuth) request.Headers.Add("Cookie",authentication.Cookie); else request.Headers.Add("Authorization", "OAuth"); } using(var response = (HttpWebResponse)request.GetResponse()) { if(response == null) throw new NullReferenceException(); var respCode = response.StatusCode; if (respCode != HttpStatusCode.OK) throw new HttpException(HttpException.HTTP_OK_NOT_RECEIVED, respCode.ToString()); var dataStream = response.GetResponseStream(); if (dataStream == null) throw new NullReferenceException(); var reader = new StreamReader(dataStream); // Read the content. var responseFromServer = new StringBuilder(""); responseFromServer.Append(reader.ReadToEnd()); reader.Close(); dataStream.Close(); response.Close(); return responseFromServer.ToString(); } }
private Request(string url, HttpMethod httpMethod, string entity = null) { _url = url; _httpMethod = httpMethod; _entity = entity; _webRequest = CreateWebRequest(_url, _entity, _httpMethod); }
public void ConfigureRequest(RavenConnectionStringOptions options, WebRequest request) { if (RequestTimeoutInMs.HasValue) request.Timeout = RequestTimeoutInMs.Value; if (options.ApiKey == null) { request.Credentials = options.Credentials ?? CredentialCache.DefaultNetworkCredentials; return; } var webRequestEventArgs = new WebRequestEventArgs { Request = request }; AbstractAuthenticator existingAuthenticator; if (authenticators.TryGetValue(GetCacheKey(options), out existingAuthenticator)) { existingAuthenticator.ConfigureRequest(this, webRequestEventArgs); } else { var basicAuthenticator = new BasicAuthenticator(options.ApiKey, enableBasicAuthenticationOverUnsecuredHttp: false); var securedAuthenticator = new SecuredAuthenticator(options.ApiKey); basicAuthenticator.ConfigureRequest(this, webRequestEventArgs); securedAuthenticator.ConfigureRequest(this, webRequestEventArgs); } }
/// <summary> /// Populates WebRequest using the operation context in telemetry item. /// </summary> /// <param name="dependencyTelemetry">Dependency telemetry item.</param> /// <param name="webRequest">Http web request.</param> internal static void SetCorrelationContextForWebRequest(DependencyTelemetry dependencyTelemetry, WebRequest webRequest) { if (dependencyTelemetry == null) { throw new ArgumentNullException("dependencyTelemetry"); } if (webRequest != null) { OperationContext context = dependencyTelemetry.Context.Operation; if (!string.IsNullOrEmpty(context.Id)) { webRequest.Headers.Add(RequestResponseHeaders.StandardRootIdHeader, context.Id); } if (!string.IsNullOrEmpty(dependencyTelemetry.Id)) { webRequest.Headers.Add(RequestResponseHeaders.StandardParentIdHeader, dependencyTelemetry.Id); } } else { DependencyCollectorEventSource.Log.WebRequestIsNullWarning(); } }
public void SignRequest(WebRequest webRequest, long contentLength) { if (webRequest == null) throw new ArgumentNullException("webRequest"); webRequest.Headers[this.headerName] = this.headerValue(); }
protected void initRequest() { request = null; response = null; jsonString = ""; uri = ""; }
public Message(WebRequest request, string methodName) { this.methodName = methodName; this.request = request; this.request.Method = "POST"; // PreAuth can't be used with NTLM afaict //this.request.PreAuthenticate=true; // must allow buffering for NTLM authentication HttpWebRequest req = request as HttpWebRequest; req.AllowWriteStreamBuffering = true; //http://blogs.x2line.com/al/archive/2005/01/04/759.aspx#780 //req.KeepAlive = false; //req.ProtocolVersion = HttpVersion.Version10; this.request.ContentType = "text/xml; charset=utf-8"; this.request.Headers.Add ("X-TFS-Version", "1.0.0.0"); this.request.Headers.Add ("accept-language", "en-US"); this.request.Headers.Add ("X-VersionControl-Instance", "ac4d8821-8927-4f07-9acf-adbf71119886"); xtw = new XmlTextWriter (request.GetRequestStream(), new UTF8Encoding (false)); //xtw.Formatting = Formatting.Indented; xtw.WriteStartDocument(); xtw.WriteStartElement("soap", "Envelope", SoapEnvelopeNamespace); xtw.WriteAttributeString("xmlns", "xsi", null, XmlSchema.InstanceNamespace); xtw.WriteAttributeString("xmlns", "xsd", null, XmlSchema.Namespace); xtw.WriteStartElement("soap", "Body", SoapEnvelopeNamespace); xtw.WriteStartElement("", methodName, MessageNamespace); }
public static WebResponse GetHttpResponse(string url, string method, CookieCollection cookies = null) { Preconditions.CheckNotNull(url); Preconditions.CheckNotNull(method); if (!(WebRequest.Create(url) is HttpWebRequest request)) { throw new InvalidOperationException($"URL : {url} is invalid because request is not HttpWebRequest"); } request.Method = method; if (cookies != null) { request.CookieContainer = new CookieContainer(); request.CookieContainer.Add(cookies); } return(request.GetResponse()); }
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 bool smsSent(string mobileNo, string message) { #region "sms" try { // 1701160171010483055 //entity id //1707161690831867495 //templet id //http://nimbusit.co.in/api/swsendSingle.asp?username=xxxx&password=xxxx&sender=senderId&sendto=919xxxx&entityID=170134xxxxxxxxx&templateID=158777xxxxxxxxxxx&message=hello // sender id //TOFOZF // string template_id = "123"; //string strUrl = "https://nimbusit.co.in/api/swsend.asp?username="******"&password="******"&sender="+SD.SMS_OPTINS+"&sendto="+mobileNo+"&message="+message; string strUrl = "http://nimbusit.co.in/api/swsendSingle.asp?username="******"&password="******"&sender=" + SD.SMS_OPTINS + "&sendto=" + mobileNo + "&entityID=" + SD.SMS_EntityId + "&templateID=" + SD.SMS_templateId + "&message=" + message + ""; /* * string strUrl = "http://nimbusit.co.in/api/swsendSingle.asp?username="******"&password="******"&sender="+SD.SMS_OPTINS+"&sendto="+mobileNo+"&entityID="+SD.SMS_EntityId+"&templateID="+SD.SMS_templateId+"&message="+message+""; */ ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; System.Net.WebRequest request = System.Net.WebRequest.Create(strUrl); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream s = (Stream)response.GetResponseStream(); StreamReader readStream = new StreamReader(s); string dataString = readStream.ReadToEnd(); s.Close(); readStream.Close(); response.Close(); return(true); } catch { return(false); } #endregion }
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> /// 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 + "/")); } } }
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); }
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; } }
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; } } }
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 static string HEADRequest(string path, string username, string password, string tagName) { try { System.Net.WebRequest request = System.Net.WebRequest.Create(path); request.Method = "HEAD"; request.Credentials = new NetworkCredential(username, password); var response = request.GetResponse(); return(response.Headers[tagName]); } catch (Exception ex) { Common.Utility.LogError(string.Format("Failed to make Head Request by path:{0}", path), ex); return(null); } }
//发起Http请求 public static string HttpPost(string url, Stream data, IDictionary<object, string> headers = null) { System.Net.WebRequest request = HttpWebRequest.Create(url); request.Method = "POST"; if (data != null) request.ContentLength = data.Length; //request.ContentType = "application/x-www-form-urlencoded;charset=utf-8"; if (headers != null) { foreach (var v in headers) { if (v.Key is HttpRequestHeader) request.Headers[(HttpRequestHeader)v.Key] = v.Value; else request.Headers[v.Key.ToString()] = v.Value; } } HttpWebResponse response = null; try { // Get the response. response = (HttpWebResponse)request.GetResponse(); // Display the status. Console.WriteLine(response.StatusDescription); // Get the stream containing content returned by the server. Stream dataStream = response.GetResponseStream(); // Open the stream using a StreamReader for easy access. StreamReader reader = new StreamReader(dataStream); // Read the content. string responseFromServer = reader.ReadToEnd(); // Display the content. Console.WriteLine(responseFromServer); // Cleanup the streams and the response. reader.Close(); dataStream.Close(); response.Close(); return responseFromServer; } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(response.StatusDescription); return e.Message; } }
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 CheckGiaLiveSAP(string mahang) { string url = "http://prd-app1.duytan.local:8100/sap/bc/ywsgpoitems?sap-client=900&MA=" + mahang; System.Net.WebRequest request = WebRequest.Create(url); //request.Credentials = new NetworkCredential("sapuser", "password"); WebResponse ws = request.GetResponse(); string jsonString = string.Empty; using (System.IO.StreamReader sreader = new System.IO.StreamReader(ws.GetResponseStream())) { jsonString = sreader.ReadToEnd(); } Context.Response.Write(JsonConvert.SerializeObject(jsonString)); }
public static bool GetVerifyMessage(string strHydroID, string strDemo, string strMessage, out string strNotMessage) { bool blnResult = false; strNotMessage = ""; string strUrlMessage = ""; if (strDemo == "SandBox") { strUrlMessage = cSettings[0].ApiSandBoxVerify; } else { strUrlMessage = cSettings[0].ApiGetVerify; } try { string strUrl = strUrlMessage + "?message=" + strMessage + "&hydro_id=" + strHydroID + "&application_id=" + cSettings[0].ApplicationID; System.Net.WebRequest request = System.Net.HttpWebRequest.Create(strUrl); request.Method = "GET"; request.ContentType = "application/json"; request.Headers.Add("Authorization", "Bearer " + cSettings[0].AccesToken); using (WebResponse response = request.GetResponse()) { using (StreamReader streamReader = new StreamReader(response.GetResponseStream())) { strNotMessage = streamReader.ReadToEnd(); string[] strSplit = strNotMessage.Split(','); strNotMessage = strSplit[0].ToString(); strNotMessage = strNotMessage.Replace("{", "").Replace("\"", "").Replace(":", " "); } } blnResult = true; } catch (Exception ex) { strNotMessage = ex.Message.ToString(); blnResult = false; } return(blnResult); }
/// <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> /// 获取外网ip /// </summary> public static string GetOutIP() { string strUrl = "http://www.ip138.com/ip2city.asp"; //获得IP的网址了 Uri uri = new Uri(strUrl); System.Net.WebRequest wr = System.Net.WebRequest.Create(uri); System.IO.Stream s = wr.GetResponse().GetResponseStream(); System.IO.StreamReader sr = new System.IO.StreamReader(s, Encoding.Default); string all = sr.ReadToEnd(); //读取网站的数据 int i = all.IndexOf("[") + 1; string tempip = all.Substring(i, 15); string ip = tempip.Replace("]", "").Replace(" ", "");//找出i //也可用 //new Regex(@"ClientIP: \[([\d.]+?)\]").Match(new System.Net.WebClient().DownloadString("http://www.skyiv.com/info/")).Groups[1].Value; return(ip); }
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 void ApplyAdditionalRequiredHeaders(System.Net.WebRequest request) { request.ContentType = "application/atom+xml;type=entry;charset=utf-8"; if (request is HttpWebRequest) { ((HttpWebRequest)request).Accept = "application/atom+xml,application/xml"; } else { request.Headers.Add("Accept", "application/atom+xml,application/xml"); } // these are not documented as required, but older emulator fails without them //request.Headers.Add("DataServiceVersion", "2.0;"); //request.Headers.Add("MaxDataServiceVersion", "2.0;NetFx"); }
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); } }
private string GetResponseResult(string url) { System.Net.WebRequest webRequest = System.Net.WebRequest.Create(url); string result; using (System.Net.HttpWebResponse httpWebResponse = (System.Net.HttpWebResponse)webRequest.GetResponse()) { using (System.IO.Stream responseStream = httpWebResponse.GetResponseStream()) { using (System.IO.StreamReader streamReader = new System.IO.StreamReader(responseStream, System.Text.Encoding.UTF8)) { result = streamReader.ReadToEnd(); } } } return(result); }
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); }
static void Main(string[] args) { //Console.Beep(); var ra = new Random(); while (true) { Console.WriteLine(DateTime.Now); SystemSounds.Beep.Play(); // pbaaphpbkehboammnlcihpemkkimdfgo // http://clients2.google.com/service/update2/crx?response=redirect&x=id%3Dpbaaphpbkehboammnlcihpemkkimdfgo%26uc%26lang%3Den-US&prod=chrome var uri = "http://clients2.google.com/service/update2/crx?response=redirect&x=id%3Dpbaaphpbkehboammnlcihpemkkimdfgo%26uc%26lang%3Den-US&prod=chrome"; System.Net.WebRequest request = System.Net.WebRequest.Create(uri); request.Method = "GET"; // The remote server returned an error: (404) Not Found. try { var r = request.GetResponse(); Console.WriteLine(new { r.ContentLength }); } catch (Exception ex) { if (ex.Message.Contains("404")) { Thread.Sleep(1000 + ra.Next(15000)); continue; } Console.WriteLine(ex); } Console.WriteLine("ready!"); Console.Title = "ready!"; Console.ReadKey(); } // The remote server returned an error: (413) Request Entity Too Large. }
private void FetchBingSupportedLanguageCodes() { try { string uriForCodes = "http://api.microsofttranslator.com/V2/Ajax.svc/GetLanguagesForTranslate"; System.Net.WebRequest translationWebRequest = System.Net.HttpWebRequest.Create(uriForCodes); // The authorization header needs to be "Bearer" + " " + the access token string headerValue = "Bearer " + AdmAccessToken._admAccessToken.access_token; translationWebRequest.Headers["Authorization"] = headerValue; // And now we call the service. When the translation is complete, we'll get the callback IAsyncResult writeRequestStreamCallback = (IAsyncResult)translationWebRequest.BeginGetResponse(new AsyncCallback(BingSupportedLanguageCodesFetched), translationWebRequest); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("Something bad happened while fetching language codes" + ex.Message); } }
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); }
/// <summary> /// Get方式 /// </summary> /// <param name="url">请求链接</param> /// <param name="encoding">编码</param> /// <returns></returns> public static string HttpGet(string url, string encoding) { string strResult = ""; try { System.Net.WebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); request.Method = "GET"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream streamReceive = response.GetResponseStream(); Encoding encode = Encoding.GetEncoding(encoding); StreamReader streamReader = new StreamReader(streamReceive, encode); strResult = streamReader.ReadToEnd(); } catch { } return(strResult); }
public string Post(string message) { System.Net.WebRequest req = System.Net.WebRequest.Create(message); req.Method = "POST"; req.Timeout = 100000; req.ContentType = "application/x-www-form-urlencoded"; byte[] sentData = Encoding.GetEncoding(1251).GetBytes(""); req.ContentLength = sentData.Length; System.IO.Stream sendStream; try { sendStream = req.GetRequestStream(); sendStream.Write(sentData, 0, sentData.Length); sendStream.Close(); } catch (WebException) { return("-2"); } System.Net.WebResponse res; try { res = req.GetResponse(); } catch (WebException we) { return("-3"); } System.IO.Stream ReceiveStream = res.GetResponseStream(); System.IO.StreamReader sr = new System.IO.StreamReader(ReceiveStream, Encoding.UTF8); //Кодировка указывается в зависимости от кодировки ответа сервера Char[] read = new Char[256]; int count = sr.Read(read, 0, 256); string Out = String.Empty; while (count > 0) { String str = new String(read, 0, count); Out += str; count = sr.Read(read, 0, 256); } return(Out); }
/// <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); } }
private string CheckCRL(string serial) { string RestCert = string.Empty; string Service_URL = "http://app.ca.tot.co.th/c_service/verify/product_status_checking_result.jsp"; //ForTEST = 6737 var Parameters = "issuer=null&searchType=serial&sn=" + serial; System.Net.WebRequest req = System.Net.WebRequest.Create(Service_URL); req.ContentType = "application/x-www-form-urlencoded"; 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.ASCII.GetBytes(Parameters); req.ContentLength = bytes.Length; try { 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) { System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream(), Encoding.Default); Encoding end = sr.CurrentEncoding; RestCert = sr.ReadToEnd().Trim(); //if (!string.IsNullOrEmpty(RestCert)) //{ // parseHTML(RestCert); //} } } catch (WebException WebEx) { RestCert = "Error:" + WebEx.Message; } catch (Exception ex) { RestCert = "Error:" + ex.Message; } return(RestCert); }
public Connect_information() { InitializeComponent(); string url = "http://checkip.dyndns.org/"; System.Net.WebRequest rq = System.Net.WebRequest.Create(url); System.Net.WebResponse resp = rq.GetResponse(); System.IO.StreamReader Sr = new System.IO.StreamReader(resp.GetResponseStream()); string responce = Sr.ReadToEnd().Trim(); string[] a = responce.Split(':'); string a2 = a[1].ToString(); string[] a3 = a2.Split('<'); string a4 = a3[0]; var Host = Dns.GetHostByName(Dns.GetHostName()); foreach (var ip in Host.AddressList) { if (ip.AddressFamily == AddressFamily.InterNetwork) { ListBox_Conncetion.Items.Add("Local ip Address " + ip.ToString()); } } ListBox_Conncetion.Items.Add("My public IP is " + a4); ListBox_Conncetion.Items.Add(""); ListBox_Conncetion.Items.Add("Listing All Network Interfaces on: " + Environment.MachineName.ToUpper()); ListBox_Conncetion.Items.Add("---------------------------------------------------------------------"); foreach (NetworkInterface x in NetworkInterface.GetAllNetworkInterfaces()) { if (x.NetworkInterfaceType == NetworkInterfaceType.Ethernet || x.NetworkInterfaceType == NetworkInterfaceType.Ethernet3Megabit || x.NetworkInterfaceType == NetworkInterfaceType.FastEthernetFx || x.NetworkInterfaceType == NetworkInterfaceType.FastEthernetT || x.NetworkInterfaceType == NetworkInterfaceType.GigabitEthernet || x.NetworkInterfaceType == NetworkInterfaceType.Wireless80211) { foreach (UnicastIPAddressInformation ip in x.GetIPProperties().UnicastAddresses) { if (ip.Address.AddressFamily == AddressFamily.InterNetwork) { ListBox_Conncetion.Items.Add(x.Description + " - " + ip.Address.ToString() + " (" + x.Name + ")"); } } } } }
public string getWebTitle(string url) { //请求资源 System.Net.WebRequest wb = System.Net.WebRequest.Create(url.Trim()); //响应请求 WebResponse webRes = null; //将返回的数据放入流中 Stream webStream = null; try { webRes = wb.GetResponse(); webStream = webRes.GetResponseStream(); } catch { return("输入的网址不存在或非法..."); } //从流中读出数据 StreamReader sr = new StreamReader(webStream, System.Text.Encoding.UTF8); //创建可变字符对象,用于保存网页数据 StringBuilder sb = new StringBuilder(); //读出数据存入可变字符中 string str = ""; while ((str = sr.ReadLine()) != null) { sb.Append(str); } //建立获取网页标题正则表达式 string regex = @"<title>.+</title>"; //返回网页标题 string title = Regex.Match(sb.ToString(), regex).ToString(); title = Regex.Replace(title, @"[<title>/]", ""); return(title); }